gpt4 book ai didi

c# - 如何仅从接口(interface)和方法名称调用方法?

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:22 25 4
gpt4 key购买 nike

在我的程序中,我们引用了另一个程序集,而那个程序集中肯定有一个实现实例。所以我们想在运行时调用它的方法。我们知道接口(interface)和方法名,但是实现实例名还不确定。如何仅从接口(interface)和方法名称调用方法?

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");
}
}
}

但反射部分不起作用,我不确定如何才能让它正常工作。

编辑:我不清楚实例名,只知道接口(interface)名和方法名。但是我知道那个程序集中肯定有一个来自接口(interface)的实现类。

最佳答案

您的错误信息非常明确:您不能创建接口(interface)的实例。想象一下,如果你写...

var x = new ISample()

... 在正常代码中。这完全没有意义

错误源于这些代码行...

Type outerInterface = Assembly.LoadAssembly("AnotherAssemblyFile").GetTypes()
.Single(f => f.Name == "ISample" && f.IsInterface == true);
Object instance = Activator.CreateInstance(outerInterface);

...在上面的 list 中,您可以找到接口(interface)本身,然后尝试实例化它。

你真正想做的是找到一个实现接口(interface)的类型并实例化它...

Type type = Assembly.Load("AnotherAssembly")
.GetTypes()
.Single(t => t.GetInterfaces().Contains(typeof(ISample)));
ISample instance = (ISample) Activator.CreateInstance(type);
string result = instance.SampleMethod("test");

...注意我是如何cast ISample 的实例——这消除了调用 GetMethod 的需要。

如果您还没有对程序集的引用,您可以这样做:

Type[] types = Assembly
.Load("AnotherAssembly")
.GetTypes();
Type sampleInterface = types
.Single(f => f.Name == "ISample" && f.IsInterface == true);
Type type = types
.Single(t => t.GetInterfaces().Contains(sampleInterface));
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("SampleMethod");
string result = (string) method.Invoke(instance, new object[] { "you will see me" });

关于c# - 如何仅从接口(interface)和方法名称调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31849816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com