开发者

CLR question. Why method overloading in C# decides that null is a string? [duplicate]

开发者 https://www.devze.com 2022-12-10 05:08 出处:网络
This question already has answers here: Closed 13 years ago. Possible Duplicate: C#: Passing null to overloaded method - which method is called?
This question already has answers here: Closed 13 years ago.

Possible Duplicate:

C#: Passing null to overloaded method - which method is called?

Here is a test case

object a = null;
var b = Convert.ToString (null);
var c = Convert.ToString (a);
string d = Convert.ToString (null); // CLR chooses Convert.ToString(string value)
string e = Convert.ToString (a); // CLR chooses Convert.ToString(object value)

The question is why CLR decides that null is interpreted as string in first case? It appears that this question was already answered here

Here is another similar case. None of these ifs are triggered

object x = null;
if (x is object)
{
    Console.Write ("x is object");
}

if (x is string)
{
    Console.Write ("x is string");
开发者_如何学JAVA}

if (null is object)
{
    Console.Write ("null is object");
}

if (null is string)
{
    Console.Write ("null is string");
}


The answer is because it must choose a reference type (null doesn't work for value types), and every string is an object, but not every object is a string. See Jon Skeet's answer to this question for more information.

In response to your second example, if a variable that is null is passed to is, it will always evaluate to false, no matter what.


In overload resolution, when faced with a choice of resolving a parameter to a base class or a derived class, the compiler will always choose the most derived class if it fits. This enables overloads which take a derived class not being ambiguous with overloads which take the base class. In this case, since string is dervied from object, string is preferred.

For details, look at Section 7.4.3 in the C# Language Specification. There's a very complex discussion there, but the basic idea is that there's an algorithm that the compiler uses to define the "best" overload, and one of the things that makes one better than the other is this:

• for at least one argument, the conversion from EX to PX is better than the conversion from EX to QX.

Reading on:

• If an implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists, C1 is the better conversion.

Since there's an implicit conversion from any derived class to its base, but not vice-versa, the rules above mean that any matching dervied-class overload always beats out a base-class parameter in an overload.

0

精彩评论

暂无评论...
验证码 换一张
取 消