简体   繁体   English

如何使用反射查找在C#中声明为虚拟的所有方法?

[英]How to find all methods that are declared as virtual in c# using reflection?

For example 例如

public class UserInfo {}

public interface IUser
{
  UserInfo Get(int id);
  string GetData(int id);
}

public class User : IUser
{
    public UserInfo Get(int id)
    {
        return null;
    }
    public virtual string GetData(int id)
    {
        return null;
    }
}

I tried the following but it returns true for both methods. 我尝试了以下方法,但两种方法均返回true。

MethodInfo[] methods=typeof(User).GetMethods();
foreach(MethodInfo method in methods)
{
   if(method.IsVirtual)
   {
      Console.WriteLine(method.Name);
   }
}

Expected Output 预期产量

GetData

Actual Output 实际产量

Get
GetData

This link is some what similar but not working in my case: use-reflection-to-find-all-public-virtual-methods-and-provide-an-override 此链接有些相似,但在我的情况下不起作用: 使用反射查找所有公共虚拟方法并提供覆盖

The problem is Get is a virtual method in that it implements IUser.Get and so is called using execution-time dispatch - I suspect, anyway. 问题是Get是一个虚拟方法,因为它实现了IUser.Get ,因此使用执行时分派进行调用 -无论如何,我怀疑。 (You haven't given us a complete program, so I've had to guess.) (您没有给我们完整的程序,所以我不得不猜测。)

If you actually want "methods that can be overridden" you also need to check MethodBase.IsFinal . 如果您实际上想要“可以覆盖的方法”,则还需要检查MethodBase.IsFinal So just change your loop to: 因此,只需将循环更改为:

foreach (MethodInfo method in methods)
{
   if (method.IsVirtual && !method.IsFinal)
   {
      Console.WriteLine(method.Name);
   }
}

Full, working sample: 完整的工作示例:

class Program
{
    static void Main(string[] args)
    {
        MethodInfo[] methods = typeof(User).GetMethods();
        foreach (var method in methods)
        {
            if (method.IsVirtual && !method.IsFinal)
            {
                Console.WriteLine(method.Name);
            }
        }
        Console.ReadLine();
    }
}

public class User : IUser
{
    public string Get(int id)
    {
        // some codes
        return null;
    }
    public virtual string GetData(int id)
    {
        // I want to find this method declared as virtual
        return null;
    }
}

public interface IUser
{
    string Get(int id);
    string GetData(int id);
}

Output: 输出:

GetData
ToString
Equals
GetHashCode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM