我有一个名为 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 似乎是可行的方法 - 唯一的问题是它需要类型的完全限定名称,即包括命名空间。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top