我正在使用以下代码创建和缓存属性访问者委托:
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