【发布时间】:2021-02-07 23:21:22
【问题描述】:
我有一个列表
List<Type> types = new List<Type>();
我将在其中存储随机类型的调用类型,包括第一个索引上的 MethodInfo。
我想做这样的事情:
types[0] == typeof(MethodInfo)
检查元素的类型是否为 MethodInfo。
我的问题是这个表达式总是计算为假,我不知道它背后的原因。
更新 完整代码:
List<Type> types = new List<Type>() { typeof(Person) };
var personMethods = typeof(Person).GetMethods().Where(m => m.GetCustomAttribute<MethodMarkerAttribute>() != null).ToArray();
foreach (var personMethod in personMethods)
{
types.Add(personMethod.GetType());
}
int counter = 0;
for (int i = 0; i < types.Count; i++)
{
if (types[i] == typeof(MethodInfo))
{
counter++;
}
}
Console.WriteLine("{0} Method info(s) were found.", counter);
Console.ReadLine();
【问题讨论】:
-
你究竟是如何将
MethodInfo放在List<Type>中的? -
如果您将类型添加为
types.Add(typeof(MethodInfo));,则var isIt = types[0] == typeof(MethodInfo);应返回true。 -
或对象的类型,如
types.Add(someObjectInstance.GetType());。 -
我上传了代码,问题是计数器停留在0,但我希望它在2。
-
GetMethods()是否找到了正确的方法?