好的,问题来了。我在比较两种不同方法的返回类型时遇到问题。
第一个方法被硬编码为特定的通用类型,因此当您获取有关方法返回类型的信息时,它包括类型。这就是我的意思。
public Task<Message> GetMessage(long id)
{
...
return await getEntityFromDbById<Message>(id); //generic type is hard coded to type Message
}
如果您获得方法信息 this.GetType().GetTypeInfo().GetDeclaredMethod("GetMessage").ReturnType.ToString()
,并查看它的返回类型,这就是您得到
System.Threading.Tasks.Task`1[Core.Models.Message]
现在,我的第二个方法是通用的,看起来像这样。
public Task<T> GetEntityById<T>(long id) where T : class, IEntity
{
...
return await getEntityFromDbById<T>(id); // generic type is passed in
}
现在,如果您获得此方法的 ReturnType 信息,您将获得
System.Threading.Tasks.Task`1[T]
我想在运行时做的是获取 T
的类型信息,并将其与仅使用 MethodInfo 类型的其他方法进行比较。这怎么可能完成了吗?
public bool compareMethods(MethodInfo method1, MethodInfo method2)
{
...
//Won't work because one method has a generic return type.
//How do you detect and compare?
return method1.ReturnType == method2.ReturnType;
}
最佳答案
给定一个类型引用,您可以使用 GetGenericArguments()
方法访问引用泛型类型参数的类型信息,该方法将返回泛型参数的类型引用数组。
在 MethodInfo
上定义了相同的方法。由于您的声明中只有一个通用参数,您实际上可以只写:
public bool compareMethods(MethodInfo method1, MethodInfo method2)
{
return method1.GetGenericArguments()[0] == method2.GetGenericArguments()[0];
}
关于c# - 如何获取给定方法的泛型参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36230297/