c# - 有没有办法判断列表中随机元素的类型是否是 MethodInfo?
问题描述
我有一个清单
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();
解决方案
我找到了答案:
methods[0].MemberType == MemberTypes.Method