简体   繁体   中英

How to invoke static method from C# class without creating instance

I have code like this:

class Program
    {
        static void Main(string[] args)
        {
            Assembly myAsm = Assembly.LoadFile(@"c:\Some.dll");
            Type myService = myAsm.GetType("SomeClass");
            String s = (String) myService.InvokeMember("SomeMethod", BindingFlags.InvokeMethod  | BindingFlags.Public,
    null, null, new object[] {"MyParam"});
        }
    }

In Some.Dll there is public static Method SomeMethod with String param returning String but I get method missing Error...

You are missing the BindingFlags.Static flag.

String s = (String) myService.InvokeMember("SomeMethod", BindingFlags.Static | BindingFlags.InvokeMethod  | BindingFlags.Public,
null, null, new object[] {"MyParam"}); 

如果您的方法是静态的,您应该使用此绑定标志:

BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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