相关疑难解决方法(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万
查看次数

使用属性名称设置属性值

可能重复:
我可以使用Reflection设置属性值吗?

当我只有属性的字符串名称时,如何使用反射设置类的静态属性?比如我有:

List<KeyValuePair<string, object>> _lObjects = GetObjectsList();

foreach(KeyValuePair<string, object> _pair in _lObjects) 
{
  //class have this static property name stored in _pair.Key
  Class1.[_pair.Key] = (cast using typeof (_pair.Value))_pair.Value;
}
Run Code Online (Sandbox Code Playgroud)

我不知道应该如何使用属性名称字符串设置属性的值.一切都充满活力.我可以使用列表中的5个项目设置5个静态属性,每个项目都有不同的类型.

谢谢你的帮助.

回答:

Type _type = Type.GetType("Namespace.AnotherNamespace.ClassName");
PropertyInfo _propertyInfo = _type.GetProperty("Field1");
_propertyInfo.SetValue(_type, _newValue, null);
Run Code Online (Sandbox Code Playgroud)

c#

24
推荐指数
2
解决办法
6万
查看次数

标签 统计

c# ×2

action ×1

expression ×1

reflection ×1

setvalue ×1