7

リフレクションを介して明示的に実装されたインターフェイス メソッド (BusinessObject2.InterfaceMethod) を呼び出したいのですが、次のコードを使用してこれを実行しようとすると、Type.InvokeMember 呼び出しに対して System.MissingMethodException が発生します。非インターフェースメソッドは問題なく動作します。これを行う方法はありますか?ありがとう。

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

namespace Example
{
    public class BusinessObject1
    {
        public int ProcessInput(string input)
        {
            Type type = Assembly.GetExecutingAssembly().GetType("Example.BusinessObject2");
            object instance = Activator.CreateInstance(type);
            instance = (IMyInterface)(instance);
            if (instance == null)
            {
                throw new InvalidOperationException("Activator.CreateInstance returned null. ");
            }

            object[] methodData = null;

            if (!string.IsNullOrEmpty(input))
            {
                methodData = new object[1];
                methodData[0] = input;
            }

            int response =
                (int)(
                    type.InvokeMember(
                        "InterfaceMethod",
                        BindingFlags.InvokeMethod | BindingFlags.Instance,
                        null,
                        instance,
                        methodData));

            return response;
        }
    }

    public interface IMyInterface
    {
        int InterfaceMethod(string input);
    }

    public class BusinessObject2 : IMyInterface
    {
        int IMyInterface.InterfaceMethod(string input)
        {
            return 0;
        }
    }
}

例外の詳細: 「メソッド 'Example.BusinessObject2.InterfaceMethod' が見つかりません。」

4

1 に答える 1

6

これは、 が をBusinessObject2明示的に実装していることが原因IMyInterfaceです。IMyInterfaceメソッドにアクセスし、その後メソッドを呼び出すには、型を使用する必要があります。

int response = (int)(typeof(IMyInterface).InvokeMember(
                    "InterfaceMethod",
                    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
                    null,
                    instance,
                    methodData));
于 2013-03-08T14:28:15.590 に答える