현재 어셈블리에서 특정 이름을 가진 C# 인터페이스 구현을 찾는 방법은 무엇입니까?
-
09-06-2019 - |
문제
나는 인터페이스라는 것을 가지고 있습니다. 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"));
다른 팁
구현에 매개 변수가 없는 생성자가 있는 경우 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가 좋은 방법인 것 같습니다. 이것의 유일한 문제는 유형의 정규화된 이름이 필요하다는 것입니다.네임스페이스를 포함합니다.
제휴하지 않습니다 StackOverflow