Microsoft introduced dynamic attribute dynamic in 4.0, so we can implement some reflection functions and greatly improve the performance.
The following is an example of reflection without using dynamic.
Class Program
{
Static Void Main ( String [] ARGs)
{
Dynamicsample = New Dynamicsample ();
// How to Get dynamicsample through reflection
VaR Add = dynamicsample. GetType (). getmethod (" Add " );
Stopwatch watch = New Stopwatch ();
Watch. Start ();
For ( Int I = 0 ; I < 100000 ; I ++)
{
Int Re = ( Int ) Add. Invoke (dynamicsample, New Object [] { 1 , 2 });
}
Watch. Stop ();
Console. writeline (WATCH. elapsedmilliseconds ); // About 200 milliseconds
Console. Read ();
}
}
Public Class Dynamicsample
{
Public String Name { Get ; Set ;}
Public Int Add ( Int A, Int B)
{
Return A + B;
}
}
I tried it several times and it took about 200 milliseconds. Then we use dynamic for reflection to see how the performance works.
Class Program
{
Static Void Main ( String [] ARGs)
{
Dynamic dynamicsample = New Dynamicsample ();
Stopwatch watch = New Stopwatch ();
Watch. Start ();
For ( Int I = 0 ; I < 100000 ; I ++)
{
Int Re = dynamicsample. Add ( 1 , 2 );
}
Watch. Stop ();
Console. writeline (WATCH. elapsedmilliseconds ); // About 50 milliseconds
Console. Read ();
}
}
Public Class Dynamicsample
{
Public String Name { Get ; Set ;}
Public Int Add ( Int A, Int B)
{
Return A + B;
}
}
Not onlyCodeReduced, and improved performance by an order of magnitude. We recommend that you try dynamic attributes when using dynamic attributes for reflection!