使用带有Delegate.CreateDelegate的值类型的C#

使用Jon Skeet的文章使reflection飞行和探索代表作为指导,我试图使用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)Delegate.CreateDelegate(typeof(Func), this, property); return propertyDelegate(); } } 

我遇到的问题是当我调用GetPropValue并传入"Prop1"作为参数时,我在调用Delegate.CreateDelegate时收到ArgumentException ,并显示消息"Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type." 当使用任何返回包含结构的基本/值类型的属性时会发生这种情况。

有人知道在这里使用参考和值类型的方法吗?

从根本上说,你的一般方法是不可能的。 你能够获取所有非值类型并将它们视为Func是依赖于逆变( FuncT相反)。 根据语言规范,逆变不支持值类型。

当然,如果您不依赖于使用该方法,问题会更容易。

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

 public object GetPropValue(string name) { return GetType().GetProperty(name).GetValue(this); } 

如果你想返回一个Func ,只要它被调用就会获取值,只需在该reflection调用周围创建一个lambda:

 public Func GetPropValue2(string name) { return () => GetType().GetProperty(name).GetValue(this); }