0

DLL内にあるクラスのインターフェイスをインスタンス化するために、リフレクション付きのプリコンパイル済みDLLを使用しようとしています。その本で試してみましたが、うまくいきません。次のようなことをしようとすると、InvalidCastExceptionがスローされます。

ICompute iCompute = (ICompute)Activator.CreateInstance(type);

もちろん、タイプはIComputeインターフェイスを実装する私のクラスです。私は立ち往生していて、何をすべきかわかりません。完全なコードは次のとおりです。

これはDLLの内容です。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication18
{
    public class ClassThatImplementsICompute : ICompute
    {
       public int sumInts(int term1, int term2)
       {
           return term1 + term2;
       }

       public int diffInts(int term1, int term2)
       {
           return term1 - term2;
       }
    }
}

実際のプログラム:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;

namespace ConsoleApplication18
{

    public interface ICompute
    {
        int sumInts(int term1, int term2);
        int diffInts(int term1, int term2);
    }



    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Loading dll...");
            Assembly assembly = Assembly.LoadFrom("mylib.dll");

            Console.WriteLine("Getting type...");
            Type type = assembly.GetType("ConsoleApplication18.ClassThatImplementsICompute");
            if (type == null) Console.WriteLine("Could not find class type");

            Console.WriteLine("Instantiating with activator...");
            //my problem!!!
            ICompute iCompute = (ICompute)Activator.CreateInstance(type);

            //code that uses those functions...



        }
    }
}

誰か助けてもらえますか?ありがとう!

4

1 に答える 1

1

問題は、を使用してアセンブリをロードする方法に関係していますAssembly.LoadFrom()

LoadFrom()IComputeキャストしようとしているインターフェイスのコンテキストとは異なるコンテキストにアセンブリをロードします。Assembly.Load()可能であれば、代わりに使用してみてください。つまり、アセンブリをbin /プローブパスフォルダに入れ、完全な厳密な名前でロードします。

いくつかの参照:http: //msdn.microsoft.com/en-us/library/dd153782.aspx http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57143.aspx( LoadFromのデメリットビット)

于 2012-10-07T00:31:07.187 に答える