Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在当前程序集中找到具有特定名称的C接口实现?_C#_Linq_Reflection_Linq To Objects - Fatal编程技术网

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

C# 如何在当前程序集中找到具有特定名称的C接口实现?,c#,linq,reflection,linq-to-objects,C#,Linq,Reflection,Linq To Objects,我有一个叫做IStep的接口,可以进行一些计算。在运行时,我想按类名选择适当的实现 // use like this: IStep step = GetStep(sName); 如果实现具有无参数构造函数,则可以使用System.Activator类来实现。除类名外,还需要指定程序集名称: IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep; 你的问题很令人困惑 如果

我有一个叫做IStep的接口,可以进行一些计算。在运行时,我想按类名选择适当的实现

// use like this: IStep step = GetStep(sName);
如果实现具有无参数构造函数,则可以使用System.Activator类来实现。除类名外,还需要指定程序集名称:

IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep;

你的问题很令人困惑

如果要查找实现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"));

根据其他人指出的,这就是我最后写的:

/// /// 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似乎是一种方法——唯一的问题是它需要类型的完全限定名,即包括名称空间