我想要使用反射來獲取接受Action<T>
參數的方法定義。我正在使用.NET核心1.1。使用反射比較通用參數類型
由於該類有兩個具有相同名稱的方法,我試圖檢查接受的參數的類型,以確保我得到正確的方法定義(而不是其他重載),但比較似乎沒有工作。
下面是一些代碼,顯示了這個問題:
using System;
using System.Linq;
using System.Reflection;
class ReflectMe {
public void SomeMethod<T>(Action<T> action) {
action(default(T));
}
public T SomeMethod<T>() {
return default(T);
}
}
class Program {
static void Main(string[] args) {
var reflectedMethod = typeof(ReflectMe).GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(m => m.Name == "SomeMethod" && m.IsGenericMethodDefinition)
.Where(m => {
var parameters = m.GetParameters();
if (parameters.Count() != 1) {
// this filters out the 1st method
return false;
}
var actionType = typeof(Action<>);
var parameterType = parameters[0].ParameterType;
if (parameterType == actionType) {
// this is always false, even if in the debugger both
// types are displayed as System.Action`1[T]
return true;
}
return false;
})
.FirstOrDefault();
}
}
的問題是,parameterType
和actionType
是不相等的,但是當我在調試器中檢查它們看起來相同。
爲什麼比較失敗?
你調試?你有**兩種**方法嗎?每種方法的**是什麼**'parameterType'? –
調試我按預期得到了兩個方法,對於這兩個參數,參數類型都是Action'1 [T]。我更新了這個問題。 –
動作<>!=動作,請參閱Titans答案 –
bgura