2008-08-21 8 views

Odpowiedz

8

Twoje pytanie jest bardzo mylące ...

Jeśli chcesz znaleźć typy, które implementują IStep, a następnie to zrobić:

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

Jeśli znasz już nazwę wymaganego typu, po prostu zrób to

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

W oparciu o to, co inni zwrócili uwagę, jest to, co skończyło się na piśmie:

 
/// 
/// 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); 
    } 
} 
0

Dobrze Assembly.CreateInstance wydaje się być droga - jedyny problem polega na tym, że musi w pełni kwalifikowaną nazwę typu, tj. obejmującą przestrzeń nazw.

Powiązane problemy