I have an Interface called IStep
that can do some computation (See " Execution in the Kingdom of Nouns "). At runtime, I want to select the appropriate implementation by class name.
// use like this: IStep step = GetStep(sName);
Your question is very confusing...
If you want to find types that implement IStep, then do this:
foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
if (!typeof(IStep).IsAssignableFrom(t)) continue;
Console.WriteLine(t.FullName + " implements " + typeof(IStep).FullName);
}
If you know already the name of the required type, just do this
IStep step = (IStep)Activator.CreateInstance(Type.GetType("MyNamespace.MyType"));
If the implementation has a parameterless constructor, you can do this using the System.Activator class. You will need to specify the assembly name in addition to the class name:
IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep;
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
Based on what others have pointed out, this is what I ended up writing:
/// /// 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); } }
Well Assembly.CreateInstance似乎是要走的路 - 唯一的问题是它需要类型的完全限定名,即包括命名空间。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.