2008-08-21 29 views

回答

8

你提的问题是非常混乱...

如果你想找到实现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")); 
1

基于人士指出别人,这是我最后写:

 
/// 
/// 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

好Assembly.CreateInstance似乎是要走的路 - 与此唯一的问题是,它需要该类型的完全限定名称,即包含名称空间。

相关问题