C# 避免不明确的匹配异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1969411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:17:49  来源:igfitidea点击:

Avoiding an ambiguous match exception

c#reflectionambiguous-call

提问by Ben Aston

I am invoking a static method Parseon a type via reflection because I do not know the type of the object at compile-time (I do know, however, it has a Parsemethod, taking a string).

我正在通过反射对类型调用静态方法Parse,因为我在编译时不知道对象的类型(但是,我知道它有一个Parse方法,接受一个字符串)。

However, I am getting an ambiguous match exception, presumably because there are a lot of overloaded Parsemethods each taking a single object (string, int, double etc.).

但是,我得到了一个不明确的匹配异常,大概是因为有很多重载的Parse方法,每个方法都采用单个对象(字符串、整数、双精度等)。

How can I be more specific in my method invocation to ensure I reach the correct method (Parse(string s)) and the exception is not thrown.

我如何在我的方法调用中更具体地确保我到达正确的方法(Parse(string s))并且不会抛出异常。

My code looks like this:

我的代码如下所示:

Type returnType = p.PropertyType;
object value = returnType.GetMethod("Parse").Invoke(null, new string[] { "1" });

采纳答案by Benjamin Podszun

Use thisoverload and use

使用重载并使用

returnType.GetMethod("Parse", new [] {typeof(string)})