Use Dynamic of. net4.0 for reflection

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.