Calling a static method using a Type

前端 未结 3 529
逝去的感伤
逝去的感伤 2020-11-30 12:33

How do I call a static method from a Type, assuming I know the value of the Type variable and the name of the static method?

public         


        
相关标签:
3条回答
  • 2020-11-30 12:54

    Check into the MethodInfo class and the GetMethod() methods on Type.

    There are a number of different overloads for different situations.

    0 讨论(0)
  • 2020-11-30 12:56

    Note, that as 10 years have passed. Personally, I would add extension method:

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

    and then i could call it with

    var result = typeof(Foo1Class).Method<string>(nameof(Foo1Class.Foo1Method));
    
    0 讨论(0)
  • 2020-11-30 12:59

    You need to call MethodInfo.Invoke method:

    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
            }
        }
    }
    

    Of course in the above example you might as well call FooClass.FooMethod as there is no point using reflection for that. The following sample makes more sense:

    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");    
    
    0 讨论(0)
提交回复
热议问题