我一直在使用委託而不是反射來測試某些對象排序,並且它對字符串屬性有效,但如果我嘗試使用Int(或DateTime),它會失敗並且拋出嘗試訪問Int或DateTime屬性時,Open Delegate失敗
錯誤綁定到目標方法。
class Program
{
static void Main(string[] args)
{
var sample = new SampleClass() { Num = 13, Text = "Sample" };
Console.WriteLine(ReadProp(sample,"Text")); //Works
Console.WriteLine(ReadProp(sample, "classProp")); //Works
Console.WriteLine(ReadProp(sample, "Num")); //Throws 'Error binding to target method.'
}
//Use a Delegate to improve speed of accessing property instead of reflection
static object ReadProp(SampleClass obj, string propName)
{
var method = obj.GetType().GetProperty(propName).GetGetMethod();
var getForProp = (Func<SampleClass, object>)Delegate.CreateDelegate(typeof(Func<SampleClass, object>), null, method);
return getForProp(obj);
}
}
//A sample class for illustration purposes
class SampleClass
{
public string Text { get; set; }
public int Num { get; set; }
public SampleClass classProp { get; set; }
}
我的問題是:爲什麼它的字符串或其他類而不是詮釋或日期時間工作?
我可以看到,如果我改變Func<SampleClass, object>
到Func<SampleClass, int>
它就會爲我詮釋工作,但我希望對象將兩個工作。
是的,我真正的代碼只創建一次委託 – deepee1 2012-03-02 21:03:40
感謝您的鏈接,我會看看。在我的情況下,我不知道設計時的返回類型,並且必須在運行時確定屬性返回類型 – deepee1 2012-03-02 21:08:32
@ deepee1:鏈接中的代碼就是這樣 - 你給它一個'MethodInfo',它給你一個'Func'。通用方法在創建委託時通過反射調用。 –
2012-03-02 21:13:03