Reflected Emit implementation

Source: Internet
Author: User
Tags emit

 

In daily development, reflection is frequently used, except for the most "heavy" original Reflection Method (not described here) and the 4.0 keyword dynamic, there are many other methods (Emit and Linq ). In the next demonstration, I will focus on the following operations. Public class User
{
Public string Username {get; set ;}
} This is a common class that cannot be any more common. All we need to do is assign values to the Username attribute. In the past reflection, this Performance may be unacceptable. First, let's talk about the first one. paste the Code directly, and the code has detailed comments. Code Delegate void SetValueDelegate (string u );
Static void Work3 ()
{
User u = new User ();

String methodName = "set_Username"; // obtain a function (naming constraints)
Var method = u. GetType (). GetMethod (methodName); // query a function
Var type = method. GetParameters () [0]. ParameterType; // return the Data type of the first parameter.

Var parameter = Expression. Parameter (type, "value"); // create an Expression parameter
// Create a call function for a specified instance, function, or Parameter
Var callExpression = Expression. Call (Expression. Constant (u), method, parameter );
// Create an expression for calling a function
Expression <SetValueDelegate> lambdaExpression = Expression. Lambda <SetValueDelegate> (callExpression, parameter );
SetValueDelegate dd = lambdaExpression. Compile (); // generate the delegate of the executable function.

Stopwatch watch = new Stopwatch ();
Watch. Start ();
For (int I = 0
Related Article

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.