反射性能 - 创建委托(属性 C#) [英] Reflection Performance - Create Delegate (Properties C#)

查看:30
本文介绍了反射性能 - 创建委托(属性 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);)

The results were highly satisfactory, about 30-40 times faster than using the conventional method (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.

我这样做是因为我的应用程序的结构导致我无法使用带有 的方法.

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; }
}

打印出来:

foo

这篇关于反射性能 - 创建委托(属性 C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆