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