【问题标题】:Is there a way to tell if a random element's type in a list is MethodInfo?有没有办法判断列表中随机元素的类型是否是 MethodInfo?
【发布时间】: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&lt;Type&gt; 中的?
  • 如果您将类型添加为types.Add(typeof(MethodInfo));,则var isIt = types[0] == typeof(MethodInfo); 应返回true
  • 或对象的类型,如types.Add(someObjectInstance.GetType());
  • 我上传了代码,问题是计数器停留在0,但我希望它在2。
  • GetMethods() 是否找到了正确的方法?

标签: c# list types


【解决方案1】:

我找到了答案:

methods[0].MemberType == MemberTypes.Method

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    相关资源
    最近更新 更多