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...
}
}
}
誰か助けてもらえますか?ありがとう!