【问题标题】:Reflection in .NET.NET 中的反射
【发布时间】:2021-11-15 08:24:24
【问题描述】:
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.AmbiguousMatchException: "Ambiguous match found)。如何准确调用类的 Call() 方法?

【问题讨论】:

标签: c# .net reflection


【解决方案1】:

您需要使用不同的方式来获取要执行的方法。例如,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[] {});

【讨论】:

猜你喜欢
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多