C# reflection - load assembly and invoke a method if it exists

后端 未结 4 541
不思量自难忘°
不思量自难忘° 2020-11-29 00:56

I want to load an assembly (its name is stored in a string), use reflection to check if it has a method called \"CustomType MyMethod(byte[] a, int b)\" and call it or throw

4条回答
  •  盖世英雄少女心
    2020-11-29 01:16

    use reflection to check if it has a method called "CustomType MyMethod(byte[] a, int b)" and call it or throw an exception otherwise

    Your current code isn't fulfilling that requirement. But you can pretty easily with something like this:

    var methodInfo = t.GetMethod("MyMethod", new Type[] { typeof(byte[]), typeof(int) });
    if (methodInfo == null) // the method doesn't exist
    {
        // throw some exception
    }
    
    var o = Activator.CreateInstance(t);
    
    var result = methodInfo.Invoke(o, params);
    

    Is this good enough, or are there better/faster/shorter ways?

    As far as I'm concerned this is the best way and there isn't really anything faster per say.

    What about constructors, given that these methods are not static - can they simply be ignored?

    You are still going to have to create an instance of t as shown in my example. This will use the default constructor with no arguments. If you need to pass arguments you can, just see the MSDN documentation and modify it as such.

提交回复
热议问题