- Cách sử dung FieldInfo
FieldInfo field = MyType.GetField("someField",BindingFlags.NonPublic | .... );
object res = field.GetValue (MyObj);
- Điều này rất là chậm để truy cập Fields thông wa FieldInfo
- Thay vào đó chung ta sẽ sử dụng LINQ Expression
public static Func<T,R> GetFieldAccessor<T,R>(string fieldName)
{
ParameterExpression param =
Expression.Parameter (typeof(T),"arg");
MemberExpression member =
Expression.Field(param, fieldName);
LambdaExpression lambda =
Expression.Lambda(typeof(Func<T,R>), member, param);
Func<T,R> compiled = (Func<T,R>)lambda.Compile();
return compiled;
}
- Usage :
Person person = new Person();
person.FirstName = "Roger";
var getFirstName = GetFieldAccessor<Person,string> ("firstName");
...
//typed access via delegate
string result = getFirstName(person);
The Reflection.FieldInfo approach took 6.2 seconds to complete.
The Compiled lambda approach took 0.013 seconds to complete.
Reference URL : http://rogeralsing.com/2008/02/26/linq-expressions-access-private-fields/
No comments:
Post a Comment