我在使用反射时遇到了性能问题.
所以我决定为我的对象的属性创建委托,到目前为止得到了这个:
TestClass cwp = new TestClass();
var propertyInt = typeof(TestClass).GetProperties().Single(obj => obj.Name == "AnyValue");
var access = BuildGetAccessor(propertyInt.GetGetMethod());
var result = access(cwp);
Run Code Online (Sandbox Code Playgroud)
static Func<object, object> BuildGetAccessor(MethodInfo method)
{
var obj = Expression.Parameter(typeof(object), "o");
Expression<Func<object, object>> expr =
Expression.Lambda<Func<object, object>>(
Expression.Convert(
Expression.Call(
Expression.Convert(obj, method.DeclaringType),
method),
typeof(object)),
obj);
return expr.Compile();
}
Run Code Online (Sandbox Code Playgroud)
结果非常令人满意,比使用传统方法快30-40倍(PropertyInfo.GetValue (obj, null);)
问题是:我怎样才能创建SetValue一个属性相同的属性?不幸的是没有办法.
我这样做是因为我不能使用方法,<T>因为我的应用程序的结构.