32

アセンブリをロードし (その名前は文字列に格納されます)、リフレクションを使用して "CustomType MyMethod(byte[] a, int b)" というメソッドがあるかどうかを確認し、それ以外の場合は呼び出すか、例外をスローします。私はこのようなことをすべきだと思いますが、誰かがそれを行う最善の方法について同じアドバイスを提供していただければ幸いです:

Assembly asm = Assembly.Load("myAssembly"); /* 1. does it matter if write myAssembly or myAssembly.dll? */

Type t = asm.GetType("myAssembly.ClassName");

// specify parameters
byte[] a = GetParamA();
int b = GetParamB();

object[] params = new object[2];
params[0] = a;
params[1] = b;

/* 2. invoke method MyMethod() which returns object "CustomType" - how do I check if it exists? */
/* 3. what's the meaning of 4th parameter (t in this case); MSDN says this is "the Object on which to invoke the specified member", but isn't this already accounted for by using t.InvokeMember()? */
CustomType result = t.InvokeMember("MyMethod", BindingFlags.InvokeMethod, null, t, params);

これで十分ですか、それともより良い/より速い/より短い方法がありますか? これらのメソッドが静的ではないことを考えると、コンストラクターはどうですか?単純に無視できますか?

void Methods() を呼び出すとき、単に t.InvokeMember(...) と記述しても問題ありませんか、それとも常に Object obj = t.InvokeMember(...) を実行する必要がありますか?

前もって感謝します。


EDIT 以下の別の回答として、実際の例を提供しました。

4

4 に答える 4

17

リフレクションを使用して、「CustomType MyMethod(byte[] a, int b)」というメソッドがあるかどうかを確認し、それを呼び出すか、そうでない場合は例外をスローします

現在のコードはその要件を満たしていません。しかし、次のようなものでかなり簡単にできます:

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);

これで十分ですか、それともより良い/より速い/より短い方法がありますか?

私に関する限り、これが最善の方法であり、言うほど速い方法はありません。

これらのメソッドが静的ではないことを考えると、コンストラクターはどうですか?単純に無視できますか?

私の例に示すように、まだインスタンスを作成する必要がありますt。これは、引数なしでデフォルトのコンストラクターを使用します。引数を渡す必要がある場合は、MSDN のドキュメントを参照して、そのように変更してください。

于 2013-01-23T11:57:23.093 に答える
6
Assembly assembly = Assembly.LoadFile("myAssembly");
        Type type = assembly.GetType("myAssembly.ClassName");
        if (type != null)
        {
            MethodInfo methodInfo = type.GetMethod("MyMethod");
            if (methodInfo != null)
            {
                object result = null;
                ParameterInfo[] parameters = methodInfo.GetParameters();
                object classInstance = Activator.CreateInstance(type, null);
                if (parameters.Length == 0)
                {
                    //This works fine
                    result = methodInfo.Invoke(classInstance, null);
                }
                else
                {
                    object[] parametersArray = new object[] { "Hello" };

                    //The invoke does NOT work it throws "Object does not match target type"             
                    result = methodInfo.Invoke(classInstance, parametersArray);
                }
            }
        }
于 2013-01-23T12:01:55.770 に答える
3

実行時に解決される動的型を使用できます。

Type type = Type.GetType(className, true);
dynamic instance = Activator.CreateInstance(type);
var response = instance.YourMethod();
于 2015-01-09T22:04:52.753 に答える