【发布时间】:2015-08-06 07:48:16
【问题描述】:
在我的程序中,我们引用了另一个程序集,并且该程序集中肯定有一个实现实例。所以我们想在运行时调用它的方法。我们知道接口和方法的名字,但是具体的实现实例名就不一定了。我如何只能从接口和方法名称调用方法?
Type outerInterface = Assembly.LoadAssembly("AnotherAssemblyFile").GetTypes()
.Single(f => f.Name == "ISample" && f.IsInterface == true);
Object instance = Activator.CreateInstance(outerInterface);
MethodInfo mi = outerInterface.GetMethod("SampleMethod");
var result = mi.Invoke(instance, new object[]{"you will see me"});
抛出异常:
An unhandled exception of type 'System.MissingMethodException' occurred in mscorlib.dll
Additional information: Cannot create an instance of an interface.
引用的汇编代码在这里:
namespace AnotherAssembly
{
public interface ISample
{
string SampleMethod(string name);
}
public class Sample : ISample
{
public string SampleMethod(string name)
{
return string.Format("{0}--{1}", name, "Alexsanda");
}
}
}
但是反射部分不起作用,我不确定如何使它正常工作。
编辑:我不清楚实例名,只知道接口名和方法名。但我知道该程序集中的接口肯定有一个实现类。
【问题讨论】:
-
请提供异常详情
-
您不能创建接口实例。您应该创建实现接口的类的实例。 IE。
Sample在你的情况下 -
Activator.CreateInstance(outerInterface);?您正在尝试创建接口的实例?你应该寻找它的实现。
标签: c# reflection