简体   繁体   English

如何在具有特定名称的当前程序集中查找C#接口的实现?

[英]How to find an implementation of a C# interface in the current assembly with a specific name?

I have an Interface called IStep that can do some computation (See " Execution in the Kingdom of Nouns "). 我有一个名为IStep的接口可以进行一些计算(参见“ 名词王国中的执行 ”)。 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: 如果要查找实现IStep的类型,请执行以下操作:

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. 如果实现具有无参数构造函数,则可以使用System.Activator类执行此操作。 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 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似乎是要走的路 - 唯一的问题是它需要类型的完全限定名,即包括命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM