Hel*_*eda 2 c# generics reflection
在下面的代码中我们有两个类,Parent该类使用泛型:
abstract class Parent<T>
{
public T Put(T id, char value)
{
return id;
}
}
class Child : Parent<int>
{
public string Get(Guid guid)
{
return "aei";
}
}
Run Code Online (Sandbox Code Playgroud)
但是IsGenericType对id参数使用反射我们得到假 ...
我认为应该是真的,对吧?
这是我的测试代码:
public static void Main(string[] args)
{
foreach (var methodInfo in typeof(Child).GetMethods())
{
if (!methodInfo.IsVirtual && methodInfo.GetParameters().Length > 0)
{
Console.WriteLine(methodInfo.Name);
foreach (var param in methodInfo.GetParameters())
{
Console.Write(" " + param.Name + " IsGenericType=");
Console.WriteLine(param.ParameterType.IsGenericType);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
并输出:
Get
guid IsGenericType=False
Put
id IsGenericType=False
value IsGenericType=False
Run Code Online (Sandbox Code Playgroud)
那么结果是对的.Child不是通用的
class Child<T> : Parent<T>
Run Code Online (Sandbox Code Playgroud)
但是源于Parent<int>.所以签名Child.Put是
int Put(int id, char value);
Run Code Online (Sandbox Code Playgroud)
所以id不是通用类型,而是类型int.
编辑:
获取该信息的方法可能是这样的:
Type childType = typeof(Child);
MethodInfo childPut = childType.GetMethod("Put");
// get the type that initially declared the method
Type declaringType = childPut.DeclaringType;
if (declaringType.IsGenericType)
{
// get the generic type definition (not the constructed Parent<int>)
Type genericType = declaringType.GetGenericTypeDefinition();
MethodInfo genericMethod = genericType.GetMethod("Put");
ParameterInfo genericParam = genericMethod.GetParameters().First();
// use IsGenericParameter - we want to know that the type is determined
// by a generic argument, not if that type argument itself is generic
Console.WriteLine(genericParam.ParameterType.IsGenericParameter);
}
Run Code Online (Sandbox Code Playgroud)
这true为您的(特殊)案例输出.我不知道您的要求,该方法应该适用于哪种类型.正如我在评论中所说,为了使这个算法能够为所有情况确定每个参数的算法,这对我来说似乎很复杂.
| 归档时间: |
|
| 查看次数: |
423 次 |
| 最近记录: |