0

project1にはclass1とinterface1があります。Class1はinterface1を実装します。interface1を使用してこのclass1メソッドをテストする別のプロジェクトがあります。ここで問題となるのは、project1.dllを動的にロードし、インターフェイスメソッドを使用してclass1メソッドを呼び出す必要があることです。これを行うには、リフレクションを使用してproject1.dllをロードしています。ここで、インターフェイスからmethodInfoを取得します。このメソッドを呼び出す前に、メソッドを呼び出すクラスのインスタンスを作成する必要があります。activator.createInstanceを使用してクラスのインスタンスを作成するには、コンストラクターのパラメーターを知る必要があります。現在、これらのコンストラクターパラメーターはカスタムタイプです。前に言ったように、dllを動的にロードする必要があります。では、アセンブリの負荷からタイプを取得する方法はありますか?または、上記のアイデアを実現するための他のアプローチはありますか?以下は私のコードです。

Assembly assembly = Assembly.LoadFrom(@"D:\Project1.dll");
Type[] typeArray = assembly.GetTypes();
object obj;

//First create the instance of the class
foreach (Type type in typeArray)
{

    if (type.Name == "Class1")
    {

        Type[] types = new Type[4];

        //I am not able to get the below customParams from the loaded assembly.
        //Is there a way to do this. Can this be done without adding reference?
        types[0] = typeof(CustompParam1);
        types[1] = typeof(CustompParam2);
        types[2] = typeof(CustompParam3);
        types[3] = typeof(CustompParam4);

        obj = Activator.CreateInstance(types);
    }
}

//use the instance of the class to invoke the method from the interface
foreach (Type type in typeArray)
{
    if (type.Name == "Interface1")
    {
        MethodInfo[] mInfo = type.GetMethods();
        foreach (MethodInfo mi in mInfo)
        {
            mi.Invoke(obj, null);
        }
    }
}
4

1 に答える 1

0

クラスインスタンスを作成するのと同じ方法で、コンストラクターパラメーターのインスタンスを取得できます。

タイプ名でそれらを検索し、パラメータータイプとしてActivator.CreateInstanceを呼び出してから、元のクラスのActivator.CreateInstanceに配置します。

于 2013-03-20T13:10:41.257 に答える