C#参数隐式转换 [英] c# parameter implicit conversion
问题描述
具有此代码:
class Program
{
static void Main(string[] args)
{
Check(3);
Console.ReadLine();
}
static void Check(int i)
{
Console.WriteLine("I am an int");
}
static void Check(long i)
{
Console.WriteLine("I am a long");
}
static void Check(byte i)
{
Console.WriteLine("I am a byte");
}
}
为什么此代码显示我是一个int"而不是我很长"?
Why this code prints "I am an int" and not "I am a long" ?
推荐答案
为什么此代码显示我是int"?而不是我很长" ?
Why this code prints "I am an int" and not "I am a long" ?
因为编译器要遵循C#5规范中从7.5.3节开始的重载解析规则.
Because the compiler goes through the rules of overload resolution, which are in the C# 5 spec, starting at section 7.5.3.
这两个都是适用的函数成员(即,它们对于参数列表都是有效的),但是Check(int)
方法更好";因为参数的类型是int
,并且身份转换是更好",所以与Check(long)
方法相比(第7.5.3.2节).而不是扩大转换范围(第7.5.3.3节).
Both of those are applicable function members (i.e. they'd both be valid for the argument list) but the Check(int)
method is "better" than the Check(long)
method (section 7.5.3.2) because the type of the argument is int
, and an identity conversion is "better" than a widening conversion (section 7.5.3.3).
鉴于从表达式E转换为类型T1的隐式转换C1和从表达式E转换为类型T2的隐式转换C2,如果满足以下至少一项条件,则C1比C2更好. :
Given an implicit conversion C1 that converts from an expression E to a type T1, and an implicit conversion C2 that converts from an expression E to a type T2, C1 is a better conversion than C2 if at least one of the following holds:
- E具有类型S,并且存在从S到T1的身份转换,但不存在从S到T2的身份转换
- ...
此处E
是int
,T1
是int
和T2
是long
.从int
到int
有一个身份转换,但是没有从int
到long
...因此适用此规则,并且从int
到int
的转换比从int
的转换要好. >到long
.
Here E
is int
, T1
is int
, and T2
is long
. There's an identity conversion from int
to int
, but not from int
to long
... therefore this rule applies, and the conversion from int
to int
is better than the conversion from int
to long
.
这篇关于C#参数隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!