我有一个接口叫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);
}
如果您知道所需类型已经名字,只是这样做
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似乎是要走的路 - 与此唯一的问题是,它需要该类型的完全限定名称,即包含名称空间。