C#将具有值类型的属性与Delegate.CreateDelegate一起使用

C#将具有值类型的属性与Delegate.CreateDelegate一起使用,c#,reflection,delegates,primitive,value-type,C#,Reflection,Delegates,Primitive,Value Type,以Jon Skeet的文章为指导,我尝试使用Delegate.CreateDelegate方法将属性复制为委托。下面是一个示例类: public class PropertyGetter { public int Prop1 {get;set;} public string Prop2 {get;set;} public object GetPropValue(string propertyName) { var property = GetTy

以Jon Skeet的文章为指导,我尝试使用Delegate.CreateDelegate方法将属性复制为委托。下面是一个示例类:

public class PropertyGetter
{
    public int Prop1 {get;set;}
    public string Prop2 {get;set;}

    public object GetPropValue(string propertyName)
    {
        var property = GetType().GetProperty(propertyName).GetGetMethod();
        propertyDelegate = (Func<object>)Delegate.CreateDelegate(typeof(Func<object>), this, property);

        return propertyDelegate();
    }
}
公共类PropertyGetter
{
公共int Prop1{get;set;}
公共字符串Prop2{get;set;}
公共对象GetPropValue(字符串propertyName)
{
var property=GetType().GetProperty(propertyName).GetMethod();
propertyDelegate=(Func)Delegate.CreateDelegate(typeof(Func),this,property);
返回PropertyLegate();
}
}
我遇到的问题是,当我调用
GetPropValue
并传入
“Prop1”
作为参数时,我在调用
Delegate.CreateDelegate
时会得到一个
ArgumentException
,并显示消息
“无法绑定到目标方法,因为其签名或安全透明性与委托类型的签名或安全透明性不兼容。”
当使用任何返回包含结构的基元/值类型的属性时,会发生这种情况


有人知道一种可以同时使用引用类型和值类型的方法吗?

基本上,您的通用方法是不可能的。您能够将所有非值类型作为
Func
处理的原因是依赖于逆变(
Func
t
相反).根据语言规范,对冲不支持值类型

当然,如果你不依赖于使用这种方法,问题就容易了

如果只想获取值,请使用
PropertyInfo.GetValue
方法:

public object GetPropValue(string name)
{
    return GetType().GetProperty(name).GetValue(this);
}
如果要返回一个
Func
,它将在每次调用时获取值,只需围绕该反射调用创建一个lambda:

public Func<object> GetPropValue2(string name)
{
    return () => GetType().GetProperty(name).GetValue(this);
}
公共函数GetPropValue2(字符串名称) { return()=>GetType().GetProperty(name).GetValue(this); }
你只是想要属性的值,还是真的想要返回一个代表getter的委托。如果是前者,就使用
PropertyInfo.GetValue
。我全神贯注于复制Jon的性能增强,甚至没有想过使用PropertyInfo.GetValue。有趣的是,我测试了Ge的性能tValue,我在问题中提到的方法,以及使用秒表直接访问属性,发现GetValue比我在问题中使用的方法更快。谢谢。