我創建並使用下面的代碼緩存屬性訪問代表創建代表:緩存屬性存取
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();
}
這是工作,並且運行良好(謝謝你的StackOverflow!),但是我想去除通過返回T和對象的Func所需的裝箱/拆箱。有沒有什麼辦法可以改變返回值,以便返回類型是T和typeofproperty的Func?
即
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();
}
注意 - 我使用VS2013和.NET 4.5
這是如何拳擊/拆箱?你只是施放了一個ref類型.. –
@ TMcKeown,如果'T'是一個'int',那就是裝箱了。 –
好的,gotcha。你必須能夠改變'代表' –