存在許多如何接收泛型方法的變體:通過 LINQ 等在所有方法串列 (Type.GetMethods()) 中搜索或通過創建委托作為方法模板。但有趣的是,為什么它不能通過反射使用經典的 GetMethod()。在這種情況下,我們的主要問題是使用所需的方法引數串列(方法簽名)創建正確的 Type[]。我能理解這是c#的限制還是在這個例子中有其他解釋?最初我們有一個類
public class MyClass
{
public static void AddLink()
{
Console.WriteLine("Hello from AddLink()");
}
public static void AddLink<T0>(UnityAction<T0> unityAction, UnityEvent<T0> unityEvent)
{
unityEvent.AddListener(unityAction);
}
public static void AddLink<T0, T1>(UnityAction<T0, T1> unityAction, UnityEvent<T0, T1> unityEvent)
{
unityEvent.AddListener(unityAction);
}
}
我們想void AddLink<T0>(UnityAction<T0> unityAction, UnityEvent<T0> unityEvent)通過使用MethodInfo method = typeof(MyClass).GetMethod("AddLink", typeParameters). 我測驗了不同的變體typeParameters
Type[] typeParameters = new Type[] {typeof(UnityAction<>), typeof(UnityEvent<>)};
Type[] typeParametersClosed = new Type[] { typeof(UnityAction<bool>), typeof(UnityEvent<bool>) };
Type[] typeParametersClosedGeneric = new Type[] { typeof(UnityAction<bool>).GetGenericTypeDefinition(), typeof(UnityEvent<bool>).GetGenericTypeDefinition()};
沒有人給出結果。我可以通過在 GetMthods() 中搜索或將委托轉換為要求型別來找到該方法:
var template = (Action<UnityAction<object>, UnityEvent<object>>)(MyClass.AddLink);
MethodInfo methodGeneric = template.Method.GetGenericMethodDefinition();
為了測驗,我決定從已建立的方法中獲取引數
Type[] typeParametersFromGeneric = GetParametersFromMethodInfo(methodGeneric);
public static Type[] GetParametersFromMethodInfo(MethodInfo method)
{
ParameterInfo[] parameterInfo = method.GetParameters();
int length = parameterInfo.Length;
Type[] parameters = new Type[length];
for (int i = 0; i < length; i )
{
parameters[i] = parameterInfo[i].ParameterType;
}
return parameters;
}
:) 之后,使用最終的 Type[](typeParametersFromGeneric) 的 GetMethod 開始作業。
我比較了所有這些 Type[](我在這里從第二個引數中洗掉了資訊,它是相同的):
![Type[] for GetMethod 獲取具有兩個引數和一個型別引數的泛型方法](https://img.uj5u.com/2021/12/22/a36128fc5b9a47b5be8c5fbf73b4b0b4.png)
主要問題是否可以從頭開始創建 Type[] (typeParametersFromGeneric)?以及為什么這是不可能的
uj5u.com熱心網友回復:
您可以使用Type.MakeGenericSignatureType并Type.MakeGenericMethodParameter(0)作為通用引數傳遞給它:
var methodInfo = typeof(MyClass)
.GetMethod(nameof(MyClass.AddLink), new[]
{
Type.MakeGenericSignatureType(typeof(UnityAction<>), Type.MakeGenericMethodParameter(0)),
Type.MakeGenericSignatureType(typeof(UnityEvent<>), Type.MakeGenericMethodParameter(0))
});
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389722.html
上一篇:Typescript通用介面陣列
