简体   繁体   English

奇怪的C#编译器行为(重载决议)

[英]Strange C# compiler behavior (overload resolution)

I've found very strange C# compiler behavior for following code: 我发现以下代码的C#编译器行为非常奇怪:

    var p1 = new SqlParameter("@p", Convert.ToInt32(1));
    var p2 = new SqlParameter("@p", 1);
    Assert.AreEqual(p1.Value, p2.Value); // PASS

    var x = 0;
    p1 = new SqlParameter("@p", Convert.ToInt32(x));
    p2 = new SqlParameter("@p", x);
    Assert.AreEqual(p1.Value, p2.Value); // PASS

    p1 = new SqlParameter("@p", Convert.ToInt32(0));
    p2 = new SqlParameter("@p", 0);
    Assert.AreEqual(p1.Value, p2.Value); // FAIL!?

In last line assert fails with following message: 在最后一行断言失败,并显示以下消息:

  Expected: 0
  But was:  null

I understand why test fails: p2 = new SqlParameter("@p", 0); 我理解为什么测试失败: p2 = new SqlParameter("@p", 0); is resolved as SqlParameter(string, SqlDbType) and for other cases as SqlParameter(string, object) . 解析为SqlParameter(string, SqlDbType) ,其他情况解析为SqlParameter(string, SqlDbType) SqlParameter(string, object) But I don't understand why this happens. 但我不明白为什么会这样。 For me it looks like a bug, but I can't believe that C# compiler could have such kind of bug. 对我来说它看起来像一个bug,但我不相信C#编译器会有这样的bug。

Any reasons for this? 有什么理由吗?

PS It seems to be a problem for any method overload with enum parameter and 0 value (SqlDbType is enum). PS对于任何带有enum参数和0值的方法重载(SqlDbType是枚举)似乎是一个问题。

Basically, the decimal integer literal 0 is implicitly convertible to all enum types (C# 4 spec §6.1.3), so the compiler determines that SqlParameter(string, SqlDbType) is an applicable function member. 基本上,十进制整数文字0可以隐式转换为所有枚举类型(C#4规范§6.1.3),因此编译器确定SqlParameter(string, SqlDbType)是适用的函数成员。 Then it has to choose the better between two candidates function members, and it picks SqlParameter(string, SqlDbType) over SqlParameter(string, object) , because SqlDbType is a more specific type than object (§7.5.3.2). 然后它必须在两个候选函数成员之间选择更好,并且它通过SqlParameter(string, object)选择SqlParameter(string, SqlDbType) SqlParameter(string, object) ,因为SqlDbType是比object更具体的类型(第7.5.3.2节)。

But I agree that in that case it's very confusing... 但我同意在那种情况下它很混乱......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM