どのように実施のC#のインタフェースの現在の組み立てを特定します。

StackOverflow https://stackoverflow.com/questions/19656

質問

私はインターフェースと呼ばれ IStep うことができる計算ください。"務執行の英国の名詞").ランタイム時において、しなければいけませんの適正な実施によるクラスの名前です。

// use like this:
IStep step = GetStep(sName);
役に立ちましたか?

解決

ご質問は非常に混乱...

求めたい方の種類を実装するIStepしい:

foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
  if (!typeof(IStep).IsAssignableFrom(t)) continue;
  Console.WriteLine(t.FullName + " implements " + typeof(IStep).FullName);
}

まっている場合での名前に必要な型は、この

IStep step = (IStep)Activator.CreateInstance(Type.GetType("MyNamespace.MyType"));

他のヒント

実装の場合は、parameterlessコンストラクタ、これを実行する事ができます。システムを利用す活性化剤。を指定する必要がありますの組み立て名前のクラス名:

IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep;

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

に基づきどの指摘の通り、私はこれを当に書き:

/// 
/// Some magic happens here: Find the correct action to take, by reflecting on types 
/// subclassed from IStep with that name.
/// 
private IStep GetStep(string sName)
{
    Assembly assembly = Assembly.GetAssembly(typeof (IStep));

    try
    {
        return (IStep) (from t in assembly.GetTypes()
                        where t.Name == sName && t.GetInterface("IStep") != null
                        select t
                        ).First().GetConstructor(new Type[] {}
                        ).Invoke(new object[] {});
    }
    catch (InvalidOperationException e)
    {
        throw new ArgumentException("Action not supported: " + sName, e);
    }
}

もます。CreateInstanceが見られるようにするには、こでのニーズの完全修飾名をタイプするを含むの名前

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top