我有以下方法:如何測試如果在PARAMS涉及存在有效的方法
public MethodInfo FancyGetMethodInfo
(object obj, string methodName, Type[] methodSignature)
{
return obj.GetType().GetMethod(methodName, methodSignature);
}
和一個例子的緣故,我有我的目標,我通過這兩種方法
public int Subtract(int a, int b) { return a - b; }
public int Add(params int[] a) { return a.Sum(); }
當我執行下面的線,我得到這些結果:
var SubMethod = FancyGetMethodInfo(obj, "Subtract",
new Type[] { typeof(int), typeof(int) });
//I get a MethodInfo
var AddMethod = FancyGetMethodInfo(obj, "Add",
new Type[] { typeof(int), typeof(int) });
//I get a Null reference
我敢肯定,這是因爲在廣告中則params的d。有沒有一種乾淨的方式來獲取我的MethodInfo的引用給我的Add方法給定一個任意大小的Type []包含ints,並且只能訪問我的FancyGetMethodInfo方法中提供的變量?
編輯: 由Jon Skeet雄辯地說,我想執行與C#編譯器在我的方法中所做的相同的綁定。它需要與子類,隱式鑄造,任意長度params,等等正常工作...
也按要求,這裏的相關鏈接是:Determining if a parameter uses "params" using reflection in C#?這將讓我儘可能知道該方法有一個參數。
我的手上沒有VS,但是你嘗試過typeof(int [])嗎? – Tigran