【问题标题】:Calling a static method using a Type使用类型调用静态方法
【发布时间】:2023-04-05 23:13:01
【问题描述】:

假设我知道Type 变量的值和静态方法的名称,我如何从Type 调用静态方法?

public class FooClass {
    public static FooMethod() {
        //do something
    }
}

public class BarClass {
    public void BarMethod(Type t) {
        FooClass.FooMethod()          //works fine
        if (t is FooClass) {
            t.FooMethod();            //should call FooClass.FooMethod(); compile error
        }
    }
}

因此,给定一个Type t,目标是在属于Type t 的类上调用FooMethod()。基本上我需要反转typeof() 运算符。

【问题讨论】:

    标签: c#


    【解决方案1】:

    你需要调用MethodInfo.Invoke方法:

    public class BarClass {
        public void BarMethod(Type t) {
            FooClass.FooMethod(); //works fine
            if (t == typeof(FooClass)) {
                t.GetMethod("FooMethod").Invoke(null, null); // (null, null) means calling static method with no parameters
            }
        }
    }
    

    当然,在上面的示例中,您也可以调用FooClass.FooMethod,因为使用反射没有意义。以下示例更有意义:

    public class BarClass {
        public void BarMethod(Type t, string method) {
            var methodInfo = t.GetMethod(method);
            if (methodInfo != null) {
                methodInfo.Invoke(null, null); // (null, null) means calling static method with no parameters
            }
        }
    }
    
    public class Foo1Class {
      static public Foo1Method(){}
    }
    public class Foo2Class {
      static public Foo2Method(){}
    }
    
    //Usage
    new BarClass().BarMethod(typeof(Foo1Class), "Foo1Method");
    new BarClass().BarMethod(typeof(Foo2Class), "Foo2Method");    
    

    【讨论】:

    • 谢谢伊戈尔,这会很好用(虽然我对 C# 很失望——它看起来完全不安全)在我的实际代码中有很多类可能在 Type 变量中,所以反射是必要的。
    【解决方案2】:

    检查 MethodInfo 类和 Type 上的 GetMethod() 方法。

    对于不同的情况,有许多不同的重载。

    【讨论】:

      【解决方案3】:

      请注意,10 年过去了。就个人而言,我会添加扩展方法:

      public static TR Method<TR>(Type t, string method, object obj = null, params object[] parameters) 
          => (TR)t.GetMethod(method)?.Invoke(obj, parameters);
      

      然后我可以调用它

      var result = typeof(Foo1Class).Method<string>(nameof(Foo1Class.Foo1Method));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-09
        • 1970-01-01
        • 1970-01-01
        • 2015-09-26
        • 2018-10-30
        • 2011-07-14
        • 2021-03-17
        相关资源
        最近更新 更多