我在使用反射时遇到性能问题。
所以我决定为我的对象的属性创建委托,到目前为止得到了:
TestClass cwp = new TestClass();
var propertyInt = typeof(TestClass).GetProperties().Single(obj => obj.Name == "AnyValue");
var access = BuildGetAccessor(propertyInt.GetGetMethod());
var result = access(cwp);
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();
}
结果非常令人满意,比使用传统方法快约 30-40 倍(PropertyInfo.GetValue (obj, null);
)
问题是:我怎样才能做一个SetValue
的属性,其工作方式相同吗?可惜没找到办法。
我这样做是因为我不能使用方法<T>
因为我的应用程序的结构。