c# - 如何调用具有方法属性的方法?

标签 c# .net

我在类中有多个方法实例,我需要快速调用和编写它们,而无需将它们添加到我的主函数中。这将如何用属性完成?

例如
我有很多不同的类都有一个叫做“调用”的方法。我想添加一个自定义属性,我可以将其添加到此方法中,然后在称为“全部调用”的不同方法中对每个类调用 invoke 方法。

类似的东西看起来像这样,但功能强大。

public class main_class
{ 
   public void invoke_all()
   {
      // call all the invokes
   }

}

public class test1
{
   [invoke]
   public void invoke()
   {
      Console.WriteLine("test1 invoked");
   }
}
public class test2
{
   [invoke]
   public void invoke()
   { 
     Console.WriteLine("test2 invoked");
   }
}

最佳答案

要调用方法,您需要实例化一个类。要实例化一个类,您需要知道类型。

所以我们需要

  • 查找所有包含用 Invoke 标记的方法的类属性
  • 然后实例化这些类
  • 调用所有标记的方法。

  • 让我们首先定义属性:
    public class InvokeAttribute : Attribute
    {
    }
    

    您可以使用此属性来标记方法:
    public class TestClass1
    {
        [Invoke]
        public void Method1()
        {
            Console.WriteLine("TestClass1->Method1");
        }
        [Invoke]
        public void Method2()
        {
            Console.WriteLine("TestClass1->Method2"););
        }
    }
    
    public class TestClass2
    {
        [Invoke]
        public void Method1()
        {
            Console.WriteLine("TestClass2->Method1");
        }
    }
    

    现在如何查找和调用这些方法:
    var methods = AppDomain.CurrentDomain.GetAssemblies() // Returns all currenlty loaded assemblies
            .SelectMany(x => x.GetTypes()) // returns all types defined in this assemblies
            .Where(x => x.IsClass) // only yields classes
            .SelectMany(x => x.GetMethods()) // returns all methods defined in those classes
            .Where(x => x.GetCustomAttributes(typeof(InvokeAttribute), false).FirstOrDefault() != null); // returns only methods that have the InvokeAttribute
    
    foreach (var method in methods) // iterate through all found methods
    {
        var obj = Activator.CreateInstance(method.DeclaringType); // Instantiate the class
        method.Invoke(obj, null); // invoke the method
    }
    

    上面的代码段将检查所有加载的程序集。 linq 查询
  • 选择所有类型并过滤所有类
  • 然后它读取这些类中定义的所有方法
  • 并检查这些方法是否标有 InvokeAttribute

  • 这给了我们一个列表 MethodInfo s。方法信息包含 DeclaringType ,这是方法在其中声明的类。

    我们可以使用 Activator.CreateInstance实例化这个类的一个对象。这仅在类具有不带参数的公共(public)构造函数时才有效。

    然后我们可以使用 MethodInfo调用先前创建的类实例上的方法。这仅在该方法没有参数时才有效。

    关于c# - 如何调用具有方法属性的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46359351/

    相关文章:

    C# - 检查字符串是否包含相同顺序的另一个字符串的字符

    c# - 通过Unity引用python脚本

    c# - 是否有可用于简单对象转换的 C# 到 Java 序列化库?

    c# - C# 集合上的排名搜索

    c# - 使用 LINQ to Objects 语句的 "a lot"是否有一些缺点?

    javascript - 在 ASP.Net web 表单/MVC 中动态加载和添加字段

    c# - 使用 .Net 如何检查哪些用户在远程服务器上打开了资源(文件/共享)?

    c# - 带有来自委托(delegate)的参数的语句 lambda

    .Net ComboBox 绑定(bind)问题

    .net - 为什么 Task.WhenAll 上的等待不抛出 AggregateException?