2008-08-21 24 views

Trả lời

8

Câu hỏi của bạn rất khó hiểu ...

Nếu bạn muốn tìm các loại thực hiện IStep, sau đó làm điều này:

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

Nếu bạn biết đã tên của các loại yêu cầu, chỉ cần làm điều này

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

Dựa trên những gì người khác đã chỉ ra, đây là những gì tôi đã kết thúc viết:

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

Vâng Assembly.CreateInstance sẽ dường như là con đường để đi - vấn đề duy nhất với điều này là cần thiết tên đầy đủ của loại, tức là bao gồm cả không gian tên.

Các vấn đề liên quan