反射性能 - 创建委托(属性C#) [英] Reflection Performance - Create Delegate (Properties C#)
本文介绍了反射性能 - 创建委托(属性C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用反射性能问题。结果
所以我决定创造我的对象的属性代表和这么远的:
I'm having performance problems with using reflection.
So I decided to create delegates for the properties of my objects and so far got this:
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
属性,它的工作方式相同的?遗憾的是没有得到的方式。
The problem is: How can I make a SetValue
of a property, which works the same way? Unfortunately did not get a way.
我这样做,是因为我不能使用方法&LT; T&GT;因为我的应用程序的结构
I am doing so because I can not use methods with <T>
because of the structure of my application.
推荐答案
这应该为你工作:
static Action<object, object> BuildSetAccessor(MethodInfo method)
{
var obj = Expression.Parameter(typeof(object), "o");
var value = Expression.Parameter(typeof(object));
Expression<Action<object, object>> expr =
Expression.Lambda<Action<object, object>>(
Expression.Call(
Expression.Convert(obj, method.DeclaringType),
method,
Expression.Convert(value, method.GetParameters()[0].ParameterType)),
obj,
value);
return expr.Compile();
}
用法:
var accessor = BuildSetAccessor(typeof(TestClass).GetProperty("MyProperty").GetSetMethod());
var instance = new TestClass();
accessor(instance, "foo");
Console.WriteLine(instance.MyProperty);
使用的TestClass
:
public class TestClass
{
public string MyProperty { get; set; }
}
打印出:
富
这篇关于反射性能 - 创建委托(属性C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文