c# - .NET 中的反射

标签 c# .net reflection

class Program
{
    static void Main(string[] args)
    {
        Type doub = typeof(Doub);
        object result = doub.InvokeMember("Call", BindingFlags.InvokeMethod, null, null, new object[] { });
    }
}

public class Doub
{
    public Collection<string> Call()
    {
        Collection<string> collection = new Collection<string>();
        return collection;
    }

    public Collection<T> Call<T>()
    {
        Collection<T> collection = new Collection<T>();
        return collection;
    }
}

我尝试调用 Call 方法,但程序无法确定要调用哪个方法。错误:(System.Reflection.AmbigouslyMatchException:“发现不明确的匹配)。如何准确调用类的 Call() 方法?

最佳答案

您需要使用不同的方式来执行该方法。例如,Type 对象有一个名为 GetMethod 的方法,具有各种重载,您可以使用允许您 specify how many generic parameters the method has 的方法。 ,例如:

Type doub = typeof(Doub);
var callMethod = doub.GetMethod("Call", 0, new Type[] {});

// You need an instance of the object to call the method on
var x = new Doub();

var result = callMethod.Invoke(x, new object[] {});

关于c# - .NET 中的反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69274560/

相关文章:

c# - 使用反射的 == 运算符

Java - 获取封闭实例

c# - 从 SqlDataReader 读取数据

c# - 如何将 DateTime 设置为 ValuesAttribute 进行单元测试?

c# - 有没有 .NET 多态数据框架

c# - 使用证书的 WCF 传输安全忽略链信任

reflection - TypeScript:检查派生类是否实现了方法

c# - 扩大引用类型之间的转换

c# - 了解 C# 中的调度程序

c# - 将泛型参数传递给非泛型方法