使用高效的 .net 反射发出

.NET 反射优化的经验分享 从而实现性能最佳化,但是如果在编译的时候你不知道方法的签名,则需要依赖动态的方法。.NET8 里面,为许多这样的情况进行了改进,以前,emitter 总是生成可以容纳 ref/out 参数的代码,但许多方法不提供这样的参数,当不需要考虑这些因素时,生成的代码可以更高效。就可以实现更好的性能。这些并没有包含所有 MethodBase.Invoke 处理的不常见错误(如特别识别和处理 Type.Missing),但对于其他所有情况,它为优化在构建时未知签名的方法的重复调用提供了一个很好的解决方案。 阅读详情

本文概述

测试结果分析

测试结果

测试代码

概述

对于vs.net 反射发出动态方法、动态类型等,原来一直认为虽然有用,但效率不如常规方法编译的,因此一直没有深入研究,直到前些天才发现,如果用法适当,其运行效率不比常规方法创建的类、方法差,甚至更高。

 我是根据MSDN中的一个示例为基础做的测试,其位置位于:

MSDN
  开发工具和语言
    Visual Studio 文档
      Visual Studio中的.net Framework编程
        .net Framework高级开发
          发出动态方法和程序集
            使用反射发出
              如何:用反射发出定义泛型方法

测试结果分析 

在测试中,共对5种调用方法进行了测试:

  1. 直接调用类的泛型静态方法
  2. 用代理调用类的泛型静态方法
  3. 用 Invoke 调用反射发出定义的新类型的泛型方法
  4. 用代理调用反射发出定义的新类型的泛型方法
  5. 用DynamicMethod调用反射发出定义的新类型的泛型方法

从测试结果可以发现一些很有趣的现象,这也与我事先预期不同:

  • 直接调用当前工程中类的方法,并不是最快的,其效率低于使用代理方式,特别是当循环10000次,参数数组长度为100时,用时相差将近一半;
  • 用 MethodInfo 的 Invoke 方法调用(上述第3种调用方式),应该是效率最低的,测试结果也显示,其比后面的4和5两种方式效率要低将近一倍,但测试结果同时显示了,当循环测试次数为10000次时,用 Invoke 方式调用反射发出定义的新类型的泛型方法(MethodInfo对象),其用时比直接调用类的静态方法还要少,在我想来,这中奇怪的结果,应该是用正常方式写的类的方法,被编译成中间代码后,比针对性的使用反射发出生成的中间代码效率低

用反射发出定义的新类型的泛型方法,获得其 MethodInfo 后,用 Invoke 方式调用效率最低,如果有合适签名的代理,则用代理调用效率最高;如果没合适签名的代理,则可以定义一个通用类型代理,形如:

public   delegate   object  FastInvokeHandler( object  target,  object [] paramters);

然后再用反射发出定义一个同该代理签名的 DynamicMethod 方法,在该方法中,将参数相关参数都压入堆栈,再调用原来的方法,之后再处理 ref 参数和返回值,完成 DynamicMethod,然后创建该动态方法的代理,调用时用该代理调用,其效率与直接调用工程内方法差不多。

 

测试结果:


=============================================
测试开始,每个测试运行10000次,参数数组长度=11
---------------------------------------------
测1:直接调用类的 Factory 方法:运行时间:67
测2:用代理直接调用类的 Factory 方法:运行时间:65
测3:用 Invoke 调用以反射发出在动态程序集中定义的泛型方法:运行时间:52
测4:用代理调用 以反射发出在动态程序集中定义的泛型方法:运行时间:25
测5:DynamicMethod调用反射发出在动态程序集中定义的泛型方法:运行时间:25
=============================================

=============================================
测试开始,每个测试运行10000次,参数数组长度=11
---------------------------------------------
测1:直接调用类的 Factory 方法:运行时间:66
测2:用代理直接调用类的 Factory 方法:运行时间:67
测3:用 Invoke 调用以反射发出在动态程序集中定义的泛型方法:运行时间:65
测4:用代理调用 以反射发出在动态程序集中定义的泛型方法:运行时间:24
测5:DynamicMethod调用反射发出在动态程序集中定义的泛型方法:运行时间:25
=============================================

=============================================
测试开始,每个测试运行10000次,参数数组长度=100
---------------------------------------------
测1:直接调用类的 Factory 方法:运行时间:127
测2:用代理直接调用类的 Factory 方法:运行时间:69
测3:用 Invoke 调用以反射发出在动态程序集中定义的泛型方法:运行时间:77
测4:用代理调用 以反射发出在动态程序集中定义的泛型方法:运行时间:46
测5:DynamicMethod调用反射发出在动态程序集中定义的泛型方法:运行时间:45
=============================================

=============================================
测试开始,每个测试运行10000次,参数数组长度=100
---------------------------------------------
测1:直接调用类的 Factory 方法:运行时间:126
测2:用代理直接调用类的 Factory 方法:运行时间:59
测3:用 Invoke 调用以反射发出在动态程序集中定义的泛型方法:运行时间:72
测4:用代理调用 以反射发出在动态程序集中定义的泛型方法:运行时间:44
测5:DynamicMethod调用反射发出在动态程序集中定义的泛型方法:运行时间:46
=============================================

=============================================
测试开始,每个测试运行100000次,参数数组长度=11
---------------------------------------------
测1:直接调用类的 Factory 方法:运行时间:342
测2:用代理直接调用类的 Factory 方法:运行时间:242
测3:用 Invoke 调用以反射发出在动态程序集中定义的泛型方法:运行时间:513
测4:用代理调用 以反射发出在动态程序集中定义的泛型方法:运行时间:245
测5:DynamicMethod调用反射发出在动态程序集中定义的泛型方法:运行时间:245
=============================================

=============================================
测试开始,每个测试运行100000次,参数数组长度=11
---------------------------------------------
测1:直接调用类的 Factory 方法:运行时间:339
测2:用代理直接调用类的 Factory 方法:运行时间:241
测3:用 Invoke 调用以反射发出在动态程序集中定义的泛型方法:运行时间:517
测4:用代理调用 以反射发出在动态程序集中定义的泛型方法:运行时间:237
测5:DynamicMethod调用反射发出在动态程序集中定义的泛型方法:运行时间:242
=============================================

=============================================
测试开始,每个测试运行100000次,参数数组长度=100
---------------------------------------------
测1:直接调用类的 Factory 方法:运行时间:568
测2:用代理直接调用类的 Factory 方法:运行时间:481
测3:用 Invoke 调用以反射发出在动态程序集中定义的泛型方法:运行时间:719
测4:用代理调用 以反射发出在动态程序集中定义的泛型方法:运行时间:455
测5:DynamicMethod调用反射发出在动态程序集中定义的泛型方法:运行时间:459
=============================================

=============================================
测试开始,每个测试运行100000次,参数数组长度=100
---------------------------------------------
测1:直接调用类的 Factory 方法:运行时间:564
测2:用代理直接调用类的 Factory 方法:运行时间:485
测3:用 Invoke 调用以反射发出在动态程序集中定义的泛型方法:运行时间:730
测4:用代理调用 以反射发出在动态程序集中定义的泛型方法:运行时间:462
测5:DynamicMethod调用反射发出在动态程序集中定义的泛型方法:运行时间:470
=============================================

=============================================
测试开始,每个测试运行100000次,参数数组长度=100
---------------------------------------------
测1:直接调用类的 Factory 方法:运行时间:588
测2:用代理直接调用类的 Factory 方法:运行时间:495
测3:用 Invoke 调用以反射发出在动态程序集中定义的泛型方法:运行时间:747
测4:用代理调用 以反射发出在动态程序集中定义的泛型方法:运行时间:462
测5:DynamicMethod调用反射发出在动态程序集中定义的泛型方法:运行时间:472
=============================================

 

测试代码

 

using  System;
using  System.Collections.Generic;
using  System.Reflection;
using  System.Reflection.Emit;
using  System.Diagnostics;

//  Declare a generic delegate that can be used to execute the 
//  finished method.
//
public   delegate  TOut D < TIn, TOut > (TIn[] input);

class  GenericMethodBuilder
{
    
//  This method shows how to declare, in Visual Basic, the generic
    
//  method this program emits. The method has two type parameters,
    
//  TInput and TOutput, the second of which must be a reference type
    
//  (class), must have a parameterless constructor (new()), and must
    
//  implement ICollection<TInput>. This interface constraint
    
//  ensures that ICollection<TInput>.Add can be used to add
    
//  elements to the TOutput object the method creates. The method 
    
//  has one formal parameter, input, which is an array of TInput. 
    
//  The elements of this array are copied to the new TOutput.
    
//
     public   static  TOutput Factory < TInput, TOutput > (TInput[] tarray)
        
where  TOutput :  class , ICollection < TInput > ,  new ()
    {
        TOutput ret 
=   new  TOutput();
        ICollection
< TInput >  ic  =  ret;

        
foreach  (TInput t  in  tarray)
        {
            ic.Add(t);
        }
        
return  ret;
    }
    
public   static   void  loopTest()
    {
        
//  用反射发出定义一个动态程序集及泛型方法
        MethodInfo bound  =  getMyGenericMethod();

        
//  Display a string representing the bound method.
        Console.WriteLine(bound);

        D
< string , List < string >>  testByDelegate  =  (D < string , List < string >> )Delegate.CreateDelegate( typeof (D < string , List < string >> ), bound);

        D
< string , List < string >>  testByDynamicMethod  =  getDelegateByDynamicMethod < string , List < string >> (bound);

        D
< string , List < string >>  testByDirectDelegate  =   new  D < string , List < string >> (Factory < string , List < string >> );

        
string  yn  =   " Y " ;
        
while  (yn == " Y " )
        {
            testOnce(bound,testByDelegate,testByDynamicMethod,testByDirectDelegate);
            Console.WriteLine(
" 继续Y/结束N? " );
            yn 
=  Console.ReadLine();
            yn 
=  yn.ToUpper();
        }
    }
    
private   static   void  testOnce(MethodInfo bound, D < string , List < string >>  testByDelegate, D < string , List < string >>  testByDynamicMethod, D < string , List < string >>  testByDirectDelegate)
    {

        
//  准备测试
         string [] para  = {  " a " ,  " b " ,  " c " ,  " d " ,  " e " ,  " f " ,  " g " ,  " h " ,  " i " ,  " j " ,  " k "  };
        
string [] para1  =   new   string [ 100 ];

        
for  ( int  i  =   0 ; i  <  para1.Length; i ++ )
            para1[i] 
=   " a_ "   +  i.ToString();
        
int  times  =   0 ;
        Console.WriteLine(
" 请输入循环次数,然后按回车 " );
        
string  read  =  Console.ReadLine();
        
try
        {
            times 
=   int .Parse(read);
        }
        
catch
        {
            times 
=   100000 ;
        }
        Console.WriteLine(
" 使用小数组(X)还是较大数组(D)?,请输入 X 或 D " );
        read 
=  Console.ReadLine();
        
if  (read.ToLower()  ==   " d " )
            para 
=  para1;

        
int  testNum  =   0 ;
        Console.WriteLine(
" ============================================= " );
        Console.WriteLine(
" 测试开始,每个测试运行{0}次,参数数组长度={1} --------------------------------------------- " , times,para.Length);
        
        
string  method;
        Stopwatch watch;
        List
< string >  retVal;

        
//  测试1
        method  =   " 直接调用类的 Factory 方法 " ;
        watch 
=   new  Stopwatch();
        watch.Start();
        
for  ( int  i  =   0 ; i  <  times; i ++ )
        {
            retVal 
=  Factory < string , List < string >> (para);
        }
        watch.Stop();
        testNum
++ ;
        Console.WriteLine(
" 测{0}:{1}:运行时间:{2} " , testNum, method, watch.ElapsedMilliseconds);

        
//  测试2
        method  =   " 用代理直接调用类的 Factory 方法 " ;
        watch 
=   new  Stopwatch();
        watch.Start();
        
for  ( int  i  =   0 ; i  <  times; i ++ )
        {
            retVal 
=  testByDirectDelegate(para);
        }
        watch.Stop();
        testNum
++ ;
        Console.WriteLine(
" 测{0}:{1}:运行时间:{2} " , testNum, method, watch.ElapsedMilliseconds);


        
//  测试3
        method  =   " 用 Invoke 调用以反射发出在动态程序集中定义的泛型方法 " ;
        watch 
=   new  Stopwatch();
        watch.Start();
        
object [] paras  =   new   object [] { para };
        
for  ( int  i  =   0 ; i  <  times; i ++ )
        {
            retVal 
=  (List < string > )bound.Invoke( null , paras);
        }
        watch.Stop();
        testNum
++ ;
        Console.WriteLine(
" 测{0}:{1}:运行时间:{2} " , testNum, method, watch.ElapsedMilliseconds);


        
//  测试4
        method  =   " 用代理调用 以反射发出在动态程序集中定义的泛型方法 " ;
        watch 
=   new  Stopwatch();
        watch.Start();
        
for  ( int  i  =   0 ; i  <  times; i ++ )
        {
            retVal 
=  testByDelegate(para);
        }
        watch.Stop();
        testNum
++ ;
        Console.WriteLine(
" 测{0}:{1}:运行时间:{2} " , testNum, method, watch.ElapsedMilliseconds);


        
//  测试5
        method  =   " DynamicMethod调用反射发出在动态程序集中定义的泛型方法 " ;
        watch 
=   new  Stopwatch();
        watch.Start();
        
for  ( int  i  =   0 ; i  <  times; i ++ )
        {
            retVal 
=  testByDynamicMethod(para);
        }
        watch.Stop();
        testNum
++ ;
        Console.WriteLine(
" 测{0}:{1}:运行时间:{2} " , testNum, method, watch.ElapsedMilliseconds);
        Console.WriteLine(
" ============================================= " );
    }
    
private   static  D < TInput, TOutput >  getDelegateByDynamicMethod < TInput, TOutput > (MethodInfo bound)
            
where  TOutput :  class , ICollection < TInput > ,  new ()
    {
        Type tInp 
=   typeof (TInput);
        Type atInp 
=  tInp.MakeArrayType();
        Type tOut 
=   typeof (TOutput);
        DynamicMethod handle 
=   new  DynamicMethod( " DynamicFactory " ,  typeof (TOutput),  new  Type[] {  typeof (TInput).MakeArrayType() }, ( typeof (GenericMethodBuilder)).Module);
        ILGenerator ilg 
=  handle.GetILGenerator();
        ilg.Emit(OpCodes.Ldarg_0);
        ilg.EmitCall(OpCodes.Call, bound, 
null );
        ilg.Emit(OpCodes.Ret);
        D
< TInput, TOutput >  ret  =  (D < TInput, TOutput > )handle.CreateDelegate( typeof (D < TInput, TOutput > ));
        
return  ret;
    }
    
private   static  MethodInfo getMyGenericMethod()
    {
        
//  The following shows the usage syntax of the C#
        
//  version of the generic method emitted by this program.
        
//  Note that the generic parameters must be specified 
        
//  explicitly, because the compiler does not have enough 
        
//  context to infer the type of TOutput. In this case, TOutput
        
//  is a generic List containing strings.
        
//  
         string [] arr  =  {  " a " ,  " b " ,  " c " ,  " d " ,  " e "  };
        List
< string >  list1  =
            GenericMethodBuilder.Factory
< string , List < string >> (arr);
        Console.WriteLine(
" The first element is: {0} " , list1[ 0 ]);


        
//  Creating a dynamic assembly requires an AssemblyName
        
//  object, and the current application domain.
        
//
        AssemblyName asmName  =   new  AssemblyName( " DemoMethodBuilder1 " );
        AppDomain domain 
=  AppDomain.CurrentDomain;
        AssemblyBuilder demoAssembly 
=
            domain.DefineDynamicAssembly(asmName,
                AssemblyBuilderAccess.RunAndSave);

        
//  Define the module that contains the code. For an 
        
//  assembly with one module, the module name is the 
        
//  assembly name plus a file extension.
        ModuleBuilder demoModule  =
            demoAssembly.DefineDynamicModule(asmName.Name,
                asmName.Name 
+   " .dll " );

        
//  Define a type to contain the method.
        TypeBuilder demoType  =
            demoModule.DefineType(
" DemoType " , TypeAttributes.Public);

        
//  Define a public static method with standard calling
        
//  conventions. Do not specify the parameter types or the
        
//  return type, because type parameters will be used for 
        
//  those types, and the type parameters have not been
        
//  defined yet.
        
//
        MethodBuilder factory  =
            demoType.DefineMethod(
" Factory " ,
                MethodAttributes.Public 
|  MethodAttributes.Static);

        
//  Defining generic type parameters for the method makes it a
        
//  generic method. To make the code easier to read, each
        
//  type parameter is copied to a variable of the same name.
        
//
         string [] typeParameterNames  =  {  " TInput " ,  " TOutput "  };
        GenericTypeParameterBuilder[] typeParameters 
=
            factory.DefineGenericParameters(typeParameterNames);

        GenericTypeParameterBuilder TInput 
=  typeParameters[ 0 ];
        GenericTypeParameterBuilder TOutput 
=  typeParameters[ 1 ];

        
//  Add special constraints.
        
//  The type parameter TOutput is constrained to be a reference
        
//  type, and to have a parameterless constructor. This ensures
        
//  that the Factory method can create the collection type.
        
//  
        TOutput.SetGenericParameterAttributes(
            GenericParameterAttributes.ReferenceTypeConstraint 
|
            GenericParameterAttributes.DefaultConstructorConstraint);

        
//  Add interface and base type constraints.
        
//  The type parameter TOutput is constrained to types that
        
//  implement the ICollection<T> interface, to ensure that
        
//  they have an Add method that can be used to add elements.
        
//
        
//  To create the constraint, first use MakeGenericType to bind 
        
//  the type parameter TInput to the ICollection<T> interface,
        
//  returning the type ICollection<TInput>, then pass
        
//  the newly created type to the SetInterfaceConstraints
        
//  method. The constraints must be passed as an array, even if
        
//  there is only one interface.
        
//
        Type icoll  =   typeof (ICollection <> );
        Type icollOfTInput 
=  icoll.MakeGenericType(TInput);
        Type[] constraints 
=  { icollOfTInput };
        TOutput.SetInterfaceConstraints(constraints);

        
//  Set parameter types for the method. The method takes
        
//  one parameter, an array of type TInput.
        Type[] parms  =  { TInput.MakeArrayType() };
        factory.SetParameters(parms);

        
//  Set the return type for the method. The return type is
        
//  the generic type parameter TOutput.
        factory.SetReturnType(TOutput);

        
//  Generate a code body for the method. 
        
//  -----------------------------------
        
//  Get a code generator and declare local variables and
        
//  labels. Save the input array to a local variable.
        
//
        ILGenerator ilgen  =  factory.GetILGenerator();

        LocalBuilder retVal 
=  ilgen.DeclareLocal(TOutput);
        LocalBuilder ic 
=  ilgen.DeclareLocal(icollOfTInput);
        LocalBuilder input 
=  ilgen.DeclareLocal(TInput.MakeArrayType());
        LocalBuilder index 
=  ilgen.DeclareLocal( typeof ( int ));

        Label enterLoop 
=  ilgen.DefineLabel();
        Label loopAgain 
=  ilgen.DefineLabel();

        ilgen.Emit(OpCodes.Ldarg_0);
        ilgen.Emit(OpCodes.Stloc_S, input);

        
//  Create an instance of TOutput, using the generic method 
        
//  overload of the Activator.CreateInstance method. 
        
//  Using this overload requires the specified type to have
        
//  a parameterless constructor, which is the reason for adding 
        
//  that constraint to TOutput. Create the constructed generic
        
//  method by passing TOutput to MakeGenericMethod. After
        
//  emitting code to call the method, emit code to store the
        
//  new TOutput in a local variable. 
        
//
        MethodInfo createInst  =
            
typeof (Activator).GetMethod( " CreateInstance " , Type.EmptyTypes);
        MethodInfo createInstOfTOutput 
=
            createInst.MakeGenericMethod(TOutput);

        ilgen.Emit(OpCodes.Call, createInstOfTOutput);
        ilgen.Emit(OpCodes.Stloc_S, retVal);

        
//  Load the reference to the TOutput object, cast it to
        
//  ICollection<TInput>, and save it.
        
//
        ilgen.Emit(OpCodes.Ldloc_S, retVal);
        ilgen.Emit(OpCodes.Box, icollOfTInput);
        ilgen.Emit(OpCodes.Castclass, icollOfTInput);
        ilgen.Emit(OpCodes.Stloc_S, ic);

        
//  Loop through the array, adding each element to the new
        
//  instance of TOutput. Note that in order to get a MethodInfo
        
//  for ICollection<TInput>.Add, it is necessary to first 
        
//  get the Add method for the generic type defintion,
        
//  ICollection<T>.Add. This is because it is not possible
        
//  to call GetMethod on icollOfTInput. The static overload of
        
//  TypeBuilder.GetMethod produces the correct MethodInfo for
        
//  the constructed type.
        
//
        MethodInfo mAddPrep  =  icoll.GetMethod( " Add " );
        MethodInfo mAdd 
=  TypeBuilder.GetMethod(icollOfTInput, mAddPrep);

        
//  Initialize the count and enter the loop.
        ilgen.Emit(OpCodes.Ldc_I4_0);
        ilgen.Emit(OpCodes.Stloc_S, index);
        ilgen.Emit(OpCodes.Br_S, enterLoop);

        
//  Mark the beginning of the loop. Push the ICollection
        
//  reference on the stack, so it will be in position for the
        
//  call to Add. Then push the array and the index on the 
        
//  stack, get the array element, and call Add (represented
        
//  by the MethodInfo mAdd) to add it to the collection.
        
//
        
//  The other ten instructions just increment the index
        
//  and test for the end of the loop. Note the MarkLabel
        
//  method, which sets the point in the code where the 
        
//  loop is entered. (See the earlier Br_S to enterLoop.)
        
//
        ilgen.MarkLabel(loopAgain);

        ilgen.Emit(OpCodes.Ldloc_S, ic);
        ilgen.Emit(OpCodes.Ldloc_S, input);
        ilgen.Emit(OpCodes.Ldloc_S, index);
        ilgen.Emit(OpCodes.Ldelem, TInput);
        ilgen.Emit(OpCodes.Callvirt, mAdd);

        ilgen.Emit(OpCodes.Ldloc_S, index);
        ilgen.Emit(OpCodes.Ldc_I4_1);
        ilgen.Emit(OpCodes.Add);
        ilgen.Emit(OpCodes.Stloc_S, index);

        ilgen.MarkLabel(enterLoop);
        ilgen.Emit(OpCodes.Ldloc_S, index);
        ilgen.Emit(OpCodes.Ldloc_S, input);
        ilgen.Emit(OpCodes.Ldlen);
        ilgen.Emit(OpCodes.Conv_I4);
        ilgen.Emit(OpCodes.Clt);
        ilgen.Emit(OpCodes.Brtrue_S, loopAgain);

        ilgen.Emit(OpCodes.Ldloc_S, retVal);
        ilgen.Emit(OpCodes.Ret);

        
//  Complete the type.
        Type dt  =  demoType.CreateType();
        
//  Save the assembly, so it can be examined with Ildasm.exe.
        demoAssembly.Save(asmName.Name  +   " .dll " );

        
//  To create a constructed generic method that can be
        
//  executed, first call the GetMethod method on the completed 
        
//  type to get the generic method definition. Call MakeGenericType
        
//  on the generic method definition to obtain the constructed
        
//  method, passing in the type arguments. In this case, the
        
//  constructed method has string for TInput and List<string>
        
//  for TOutput. 
        
//
        MethodInfo m  =  dt.GetMethod( " Factory " );
        MethodInfo bound 
=
            m.MakeGenericMethod(
typeof ( string ),  typeof (List < string > ));
        
return  bound;
    }
}

/*  This code example produces the following output:

The first element is: a
System.Collections.Generic.List`1[System.String] Factory[String,List`1](System.String[])
The first element is: a
The first element is: a
 
*/

.NET 反射机制深度解析 **摘要**: 本文系统解析了.NET中的反射机制与动态绑定原理。前期绑定在编译时确定类型,确保安全高效但缺乏灵活性;后期绑定(如反射)支持运行时动态解析,但存在性能瓶颈。反射通过元数据表查询和构建类型系统,其性能损耗主要来自动态解析、调用开销及无法JIT优化。优化方案包括缓存元数据对象、使用Emit动态生成代码、Expression Trees编译表达式树,以及.NET 8的UnsafeAccessor特性(直接内存访问,性能接近原生调用)。文章还探讨了分层设计、AOP等架构建议,并展望.NET 9对 阅读详情

相关推荐

.NET Core反射7大绝技,你的代码为何还不会“变形”?

通过上述介绍,相信你现在应该对.NET Core中的反射有了更深入的理解。尽管它看起来有些复杂,但只要掌握了正确的方法,就能轻松驾驭这项强大的技术。记住,最好的反射并不是总是使用反射,而是知道何时以及如何恰当地应用它。希望今天的分享能够帮助你在未来的项目中写出更加灵活且高效的代码!怎么样?这篇文章是不是既专业又有趣呢?期待未来能看到更多精彩的创作诞生在你们手中。祝你好运,加油吧,未来的软件大师们!

java专栏 1766

动态反射

在我们之前的文章,反射的第一部分:发现和执行里,我们已经介绍了System.Reflection命名空间及其包含的类,开发人员使用这些类可以查看程序集的元数据,并且可以在运行时查找和发现类型,甚至可以调用发现的代码。在这篇文章中,我们将探讨反射的高级功能:Emit,它具有在运行时

巴萨,足球的艺术 1009

63、.NET 开发中的程序集与反射技术

本文详细探讨了 .NET 开发中的程序集与反射技术。首先介绍了 .NET 版本的选择及其影响,接着深入解析了程序集的定义、命名、部署和加载机制。随后全面阐述了反射的概念、应用场景、与部署机制的关系,以及相关的警告和处理方式。文章还详细分析了反射 API 中的核心类、Assembly 类的作用及使用方法,并通过插件系统、单元测试框架和配置管理等实际案例展示了反射的强大功能。最后讨论了反射的性能开销及优化策略,并给出了开发中的实际应用建议。通过本文,开发者可以全面掌握 .NET 中程序集与反射的核心知识,从而构

melon的博客 130

反射发出--Emit

"反射"和"放射发出(Emit)"的关系 相信反射大家都不陌生,我也曾写过关于反射的文章,大家有兴趣可以看看,但是今天要说的不是"反射"而是"反射发出(Emit)"。我们知道反射的主要功能是获得对象的信息、调用对象的方法等;而反射发出的主要功能是动态的创建对象。那么是不是二者就没有关系呢?事实上二者不经有关系而且关系十分密切。从命名空间我们就可以看出来,反射处于命名空间下,而反射发出Emit处于命名空间下,它的功能虽然主要是动态创建对象,但是很多反射能够完成的工作它也可以完成而且速度更快(实现当然较反射而

Kenshin Cui's Blog 4970

基于.NET反射技术动态调用DLL方法实战详解

反射不是银弹,但它是一种战略级工具。它赋予程序以“自省”和“进化”的能力,使得系统不再僵化,而是可以随着业务发展不断延展。但正如所有强大武器一样,它也需要敬畏之心:- 不滥用;- 做缓存;- 加防护;- 写日志。当你能在插件系统、IOC容器、AOP框架中游刃有余地运用反射时,你就不再是普通的开发者,而是系统架构的缔造者。所以,下次产品经理又提新需求时,你可以淡定地说一句:“没问题,我已经预留了扩展点。”😎毕竟,真正的高手,从不怕变化。

weixin_36151775的博客 707

.net高级应用 使用反射发出

本示例说明如何使用反射发出。反射发出是一种运行库特征,允许代码创建动态程序集、模块和类型。可以动态地创建这些类型的实例加以使用,或者使用反射发出生成程序集并以可执行文件或 DLL 形式存储到磁盘上。

【转】反射

反射是.NET中的重要机制,通过反射,可以在运行时获得程序或程序集中每一个类型(包括类、结构、委托、接口和枚举等)的成员和成员的信息。有了反射,即可对每一个类型了如指掌。另外我还可以直接创建对象,即使这个对象的类型在编译时还不知道。 反射的用途: (1)使用Assembly定义和加载程序集,加载在程序集清单中列出模块,以及从此程序集中查找类型并创建该类型的实例。 (2)使用M...

weixin_30312563的博客 562

.NET+Vue企业级RBAC权限平台:开箱即用的生产就绪方案

RBAC(基于角色的访问控制)是企业系统安全治理的基础模型,其核心在于将用户、角色与权限解耦,通过动态能力组合实现细粒度管控。在真实工程中,RBAC需突破静态角色限制,支持时间维度授权、前后端双重鉴权、行级数据范围控制等关键能力。本文聚焦于一套已落地金融、政务、制造等多行业的生产级实现——基于.NET Minimal API与Vue 3的前后端分离架构,提供菜单/按钮/接口/数据四层权限控制,内置滑动过期JWT、Redis权限缓存、动态路由加载与权限指令等开箱即用能力,显著降低权限配置与审计成本。

weixin_33326218的博客 286

杂记

1.结构内部的变量在赋值之前不能调用,但是可以部分赋值即不使用未赋值的字段 bool System.Boolean 4Byte 32bit布尔型变量 逻辑值,true或者false,默认值为false byte System.Byte 1Byte 8bit无符号整数无符号的字节,所存储的值的范围是0~255,默认值为0 ...

weixin_34259159的博客 120

手把手教你用HiNet实现图像隐藏:可逆神经网络实战指南(附代码)

本文提供了一份基于HiNet框架实现图像隐藏的实战指南。通过详细解析可逆神经网络原理,手把手指导环境搭建、模型构建、损失函数设计及训练流程,并附有完整代码。该方法利用单个可逆网络统一隐藏与恢复过程,结合小波变换提升隐蔽性,为信息隐藏应用提供了高效解决方案。

rgv234567的博客 437

GD32F450以太网(1):ETH 外设接口简介

GD32F450以太网ETH MAC外设接口简介

Zhichao_Zhang的博客 1万+

详解(C#) .NET反射中的BindingFlags以及常用的BindingFlags使用方式

@[toc](详解(C#) .NET反射中的BindingFlags以及常用的BindingFlags使用方式) 使用 .NET 的反射 API 时,通常会要求我们传入一个BindingFlags参数用于指定反射查找的范围。不过如果对反射不熟的话,第一次写反射很容易写错导致找不到需要的类型成员。 本文介绍BindingFlags中的各个枚举标记的含义、用途,以及常用的组合使用方式。 所有的BindingFlags 默认值 // 默认值 Default 查找 这些标记用于反射的时候查找类型成员: // 表示

天富儿的博客 6182

ZYNQ出现问题及解决办法汇总(一直更新)

问题目录使用软件及开发板版本一,vitis在build project时卡住。二,Could not find FPGA device on the board for connection 'Local'三,FPGA configuration failed:DONE PIN is not high四,Could not find ARM device on the board for connection 'Local' 使用软件及开发板版本 开发板:MZ7XA-7020 软件:vitis2020.2(

qq_45057368的博客 1万+

Albedo:.NET反射编程的统一抽象库

Albedo:.NET反射编程的统一抽象库 项目介绍 Albedo是一个面向.NET开发者的开源库,旨在通过提供一组通用的抽象和工具,使反射编程更加一致和高效。该项目最近由Mark Seemann转移到了AlbedoOrg组织进行维护,并进行了命名空间的调整。Albedo的核心目标是解决.NET反射API缺乏统一抽象的问题,通过定义一组通用的接口和模式,使得反射操作更加灵活和易于管理。 项目技术分...

gitblog_00654的博客 904

SHMOO测试详解:从DDR Training到Margin分析

SHMOO测试详解:从DDR Training到Margin分析

天赐好车的博客 218

第一章 千牛实时获取消息之ws服务端搭建

以上就是今天要讲的内容,本文仅仅简单介绍了ws服务端的搭建,后面将介绍ws客户端的搭建和配合ws服务器的测试。

不想说话的树专栏 1859

反思.NET中的反射机制

  清晰的组件化目标是否因在库间共享过多类型信息而落空?或许您需要高效的强类型化数据存储,但如果每次对象模型发展后都需要更新您的数据库架构,那会耗费很大成本,所以您更愿意在运行时推断出其类型架构吗?您需要交付能接受任意用户对象的组件,并以某种智能化的方式处理它们吗?您希望库的调方者能以编程方式向您说明它们的类型吗?   如果您发现自己在苦苦维持强类型化数据结构的同时,又冀望于最大化运行时灵活性,那

TonyWang的专栏 788

在 SAP 系统中设置成本中心(Cost Center)和利润中心(Profit Center)需在管理会计(CO)模块中完成,涉及主数据创建、组织结构配置等步骤

本文详细介绍了SAP系统中成本中心和利润中心的设置流程。成本中心设置包括:配置成本控制范围、定义标准层次结构、创建主数据(KS01/KS02/KS03)等步骤。利润中心设置需先激活利润中心会计功能,再定义标准层次并创建主数据(KE01/KE02/KE03)。关键是将成本中心与利润中心关联,实现成本数据自动流向利润中心。最后可通过相关报表验证设置是否生效。整个流程强调主数据创建和组织结构关联,以实现成本归集和利润分析功能。

金牌架构师 2237

反射发出动态类型(上)

引言   动态类型(Dynamic Types)可以向框架开发者提供高效的抽象编程模型,而不会产生通常因抽象而导致的性能损失。通过对面向接口编程和工厂设计模式的使用,可以开发一个框架,它既享有抽象编程模型通用的好处,同时也兼具硬编码逻辑的性能优势。   动态类型工厂使用程序基本元数据,确定以最佳的方式在运行时建立新类型。类代码被直接“发出”到内存中的程序集中,无需通过.NET语言特定...

airis2014的专栏 288

YOLO26改进策略【YOLO和Mamba】| CVPR 2025:EfficientViM 压缩隐藏状态空间进行通道混合、单头设计减少内存操作,提升目标检测效率与精度

本文记录的是利用模块优化的目标检测网络模型。EfficientViM Block(基于隐藏状态混合器的状态空间对偶性模块) 的设计旨在,提升特征提取效率,同时兼顾全局依赖捕捉与局部细节保留。本文将深入研究的原理,并将其应用到中,通过重构特征提取流程、减少内存绑定操作、融合多阶段特征,增强模型在资源受限环境下的检测性能与速度。EfficientViM: Efficient Vision Mamba with Hidden State Mixer based State Space DualityEfficie

Limiiiing的博客 411

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

.Net反射

以下转载自:http://www.cnblogs.com/zhouyinhui/archive/2007/08/17/859152.html反射之反思 Mike Repasshttp://msdn.microsoft.com/msdnmag/issues/07/06/CLRInsideOut/default.aspx?loc=en清 晰的组件化目标是否因在库间共享过多类型信息而落空?或许您需要高效

yc_8301的专栏 2758

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

dnSpy.NET反编译工具:让.NET开发更高效

dnSpy.NET反编译工具:让.NET开发更高效 【下载地址】dnSpy.NET反编译工具 dnSpy.NET是一款功能强大的.NET反编译工具,专为Windows 64位系统设计,提供简体中文界面,操作简便。该工具免安装,绿色便携,支持查看、编辑和调试.NET程序集,适用于.NET Framework 4.5及以上版...

gitblog_06752的博客 717

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

说说.NET中的反射

   反射是个很有趣的东西。而有趣的东西,大都可以展开联想,可以海阔开空。   西游记中,孙猴子会七十二变。反射好像也可以。   神笔马良笔下,万物复活,呵呵,反射有时候就是那只笔。    第一次接触Java时,最令我惊讶的是它的反射。   第一次接触.NET时,又见反射。   正所谓,一回生,二回熟,不再大惊小怪之后,似乎应该仔细想一想了。   说半天,反射究竟是啥?    歪一下头,闭

石头记 3178

ASP.NET Core反射应用:动态类型处理

在现代Web开发中,动态性和灵活性是至关重要的需求。ASP.NET Core通过强大的反射(Reflection)机制,为开发者提供了处理动态类型、运行时类型发现和动态方法调用的能力。本文将深入探讨ASP.NET Core中反射的应用,特别是动态类型处理的最佳实践和性能优化策略。 ## 反射基础概念 ### 什么是反射? 反射(Reflection)是.NET框架提供的一种机制,允许程序在运...

gitblog_00215的博客 1045

【亲测免费】 深度克隆之选:DeepCopy——.NET对象复制的高效工具

深度克隆之选:DeepCopy——.NET对象复制的高效工具 在.net开发领域,处理复杂对象结构时,如何有效地进行深拷贝一直是一个值得探讨的话题。今天,让我们一同揭开【DeepCopy】库的神秘面纱,这是一款简单而高效的.NET对象深度复制库,由Reuben Bond在其深入的技术博客中首次公开讨论(阅读原文)。对于那些在应用层深陷对象引用泥潭中的开发者们,DeepCopy无疑是一场及时雨。 项...

gitblog_00882的博客 1195

EF.使用反射解决实体类型转换问题

原文地址:http://www.cnblogs.com/Ewait/archive/2009/04/03/1428748.html我在做一个以Northwind为数据库,使用EDM、ASP.NET MVC1.0框架的示例项目。项目刚刚开始,目前在做一些技术测试。当对实体层进行操作时,问题来了。问题:对对象集进行查询的时候,我们往往不需要查询所有的字段,但返回的时候却要返回这个对象或对象结合。这是我们该如何做?例如:Categories这个表(在EDM中为Category类)中包含了Picture这个字段,P

heredes的专栏 3737
上一篇: Ajax 应用的思考
下一篇: Asp.net 中从服务端代码中通过Request可得到的路径
IsMe
博客等级 码龄25年 4粉丝 36原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址