【问题标题】:How compiler select method between 2 with similar signature?编译器如何在具有相似签名的 2 之间选择方法?
【发布时间】:2018-11-21 12:03:49
【问题描述】:

我有枚举

public enum ContentMIMEType
{
    [StringValue("application/vnd.ms-excel")]
    Xls,

    [StringValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")]
    Xlsx
}

在扩展中,我有两种获取属性值的方法:

public static string GetStringValue<TFrom>(this TFrom enumValue) 
            where TFrom : struct, IConvertible
{
    ...
}

public static string GetStringValue(this Enum @enum)
{
    ...
}

这些方法有不同的签名,但是当我执行下一个操作时ContentMIMEType.Xlsx.GetStringValue()第一个方法被采用。

为什么会发生这种情况,因为对我来说第二种方法的执行更加明显(尝试更改排序顺序,但没有帮助)。

【问题讨论】:

  • 这是重载解析的工作方式。例如,请参阅 this 答案 - 它是针对空参数的情况编写的,但解析的工作方式相同。

标签: c# .net enums attributes iconvertible


【解决方案1】:

Here 更多。

来自网站:

当你有两个相同的方法时会发生重载 名称但不同的签名。在编译时,编译器工作 根据编译时的类型,它将调用哪个 参数和方法调用的目标。

当编译器无法推断出哪个是正确的时,编译器返回错误。

编辑

基于Constraints on type parametersEnum Class 枚举是结构和实现IConvertible 因此满足要求和编译器使用首先匹配。与 Enum 没有冲突,因为 Enum 在继承层次结构中比 struct 更喜欢。

【讨论】:

  • 在我的情况下,struct, IConvertibleEnum 更具体,对吧?
【解决方案2】:

签名:

public static string GetStringValue<TFrom>(this TFrom enumValue) 

是泛型签名,表示允许被视为:

public static string GetStringValue<ContentMIMEType>(this ContentMIMEType enumValue) 

比以下更具体:

public static string GetStringValue(this Enum @enum)

因此是选择的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多