小编Ste*_*e G的帖子

创建用于缓存属性访问器的委托

我正在使用以下代码创建和缓存属性访问者委托:

    static Delegate CreateGetterDelegate<T>(PropertyInfo propertyInfo)
    {
        if (typeof(T) != propertyInfo.DeclaringType)
        {
            throw new ArgumentException();
        }

        var instance = Expression.Parameter(propertyInfo.DeclaringType);
        var property = Expression.Property(instance, propertyInfo);
        var convert = Expression.TypeAs(property, typeof(object));
        return (Func<T, object>)Expression.Lambda(convert, instance).Compile();
    }
Run Code Online (Sandbox Code Playgroud)

这是工作和运作良好(谢谢StackOverflow!),但是我想通过返回T和对象的Func来删除所需的装箱/拆箱.有没有办法改变返回,以便返回类型是T的Func和typeofproperty?

    static Delegate CreateGetterDelegate<T>(PropertyInfo propertyInfo)
    {
        if (typeof(T) != propertyInfo.DeclaringType)
        {
            throw new ArgumentException();
        }

        ... some magic happening here ...

        return (Func<T, typeofproperty>)Expression.Lambda(...more magic...).Compile();
    }
Run Code Online (Sandbox Code Playgroud)

注意 - 我正在使用VS2013和.NET 4.5

c# properties expression-trees

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

标签 统计

c# ×1

expression-trees ×1

properties ×1