【问题标题】:How can I get a method that has an out parameter?如何获得具有 out 参数的方法?
【发布时间】:2014-06-03 07:15:45
【问题描述】:

假设我在一个类中有两个方法,如下所示:

class Foo
{
    public void Convert(string s, int x){ }

    public void Convert(string s, double x) { }
}

如果我使用:

var method = typeof (Foo)
            .GetMethod("Convert", new[] {typeof (string), typeof (int)});

我得到了正确的方法。但是如果我在第一种方法中更改 x 并使其成为 out 参数:

public void Convert(string s, out int x) { }

然后我得到第二种方法Convert(string s, double x)

我不明白为什么它不返回第一个方法或至少null 而不是第二个?第二种方法的签名与我提供的类型不匹配。在第二种情况下如何获得正确的方法?有没有办法直接获取?我知道我可以获取所有方法,然后根据参数类型对其进行过滤,但我认为应该有一种直接的方法,但我错过了它......

【问题讨论】:

    标签: c# reflection parameters out


    【解决方案1】:

    尝试使用TypeMakeByRefType方法:

    var method = typeof (Foo)
                .GetMethod("Convert", new[] { typeof(string), typeof(int).MakeByRefType() });
    

    【讨论】:

    • 这是有效的,但仍然没有解释为什么我得到第二种方法而不是 null
    • 是的,我明白了。这是一个很好的问题。也许是因为Implicit Numeric Conversions...
    • 是的,我现在想通了,并为此添加了另一个答案 :) 我接受了这个无论如何你很快并回答了实际问题:)
    【解决方案2】:

    我知道为什么它不返回 null,原因是 doubleint 之间存在隐式转换,这就是为什么它与第二种方法相匹配。

    当我将第二种方法的参数更改为无法转换为int 的类型时,例如。 DateTime,我得到null,当我尝试使用float 时,我得到了相同的方法,因为int 也可以转换为float

    【讨论】:

      猜你喜欢
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      相关资源
      最近更新 更多