일부 계산을 수행 할 수있는 IStep
이라는 인터페이스가 있습니다 ("Execution in the Kingdom of Nouns"참조). 런타임에 클래스 이름별로 적절한 구현을 선택하려고합니다.특정 이름을 가진 현재 어셈블리에서 C# 인터페이스의 구현을 찾는 방법은 무엇입니까?
// use like this: IStep step = GetStep(sName);
일부 계산을 수행 할 수있는 IStep
이라는 인터페이스가 있습니다 ("Execution in the Kingdom of Nouns"참조). 런타임에 클래스 이름별로 적절한 구현을 선택하려고합니다.특정 이름을 가진 현재 어셈블리에서 C# 인터페이스의 구현을 찾는 방법은 무엇입니까?
// 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);
}
당신이 필요한 유형의 이미 이름을 알고 있다면, 그냥이
0123을 이렇게IStep step = (IStep)Activator.CreateInstance(Type.GetType("MyNamespace.MyType"));
이 내가 쓰기 결국 무엇을 지적 것을 다른 사람을 바탕으로
구현에 매개 변수없는 생성자가있는 경우 System.Activator 클래스를 사용하여이 작업을 수행 할 수 있습니다. 당신은 클래스 이름에 추가하여 어셈블리 이름을 지정해야합니다 :
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); } }
잘 Assembly.CreateInstance 갈 방법이있을 것 같다 -이 유일한 문제는 그것이 필요가 있다는 것입니다 이름 공간을 포함한 유형의 정규화 된 이름.