通常、すべてのクラスを許可します。これを動的にインスタンス化し、共通のインターフェイスを実装しますIMyInterface
。次のようにクラス名文字列からインスタンスを作成できます。
Assembly asm = Assembly.GetExecutingAssembly();
string classname = "MyNamespace.MyClass";
Type classtype = asm.GetType(classname);
// Constructor without parameters
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype);
// With parameters (eg. first: string, second: int):
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype,
new object[]{
(object)"param1",
(object)5
});
共通のインターフェイスを持っていなくても、メソッドの名前 (文字列として) を知っている場合でも、次のようにメソッドを呼び出すことができます (プロパティ、イベントなどについては非常に似ています)。
object instance = Activator.CreateInstance(classtype);
int result = (int)classtype.GetMethod("TwoTimes").Invoke(instance,
new object[] { 15 });
// result = 30
例のクラス:
namespace MyNamespace
{
public class MyClass
{
public MyClass(string s, int i) { }
public int TwoTimes(int i)
{
return i * 2;
}
}
}