相关疑难解决方法(0)

反射性能 - 创建代理(属性C#)

我在使用反射时遇到了性能问题.
所以我决定为我的对象的属性创建委托,到目前为止得到了这个:

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>因为我的应用程序的结构.

c# reflection expression action setvalue

25
推荐指数
2
解决办法
1万
查看次数

标签 统计

action ×1

c# ×1

expression ×1

reflection ×1

setvalue ×1