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");
}
}
为什么此代码打印 "I am an int" 而不是 "I am a long"?
Why this code prints "I am an int" and not "I am a long" ?
因为编译器遵循 C# 5 规范中的重载决策规则,从第 7.5.3 节开始。
这两个都是适用的函数成员(即它们都对参数列表有效)但是 Check(int)
方法比 Check(long)
方法(第 7.5.3.2 节),因为参数的类型是 int
,并且恒等式转换比扩大转换“更好”(第 7.5.3.3 节)。
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 has a type S and an identity conversion exists from S to T1 but not from S to T2
- ...
这里E
是int
,T1
是int
,T2
是long
。存在从 int
到 int
的身份转换,但不是从 int
到 long
... 因此适用此规则,并且从 int
到 int
优于从 int
到 long
.
的转换
有这个代码:
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");
}
}
为什么此代码打印 "I am an int" 而不是 "I am a long"?
Why this code prints "I am an int" and not "I am a long" ?
因为编译器遵循 C# 5 规范中的重载决策规则,从第 7.5.3 节开始。
这两个都是适用的函数成员(即它们都对参数列表有效)但是 Check(int)
方法比 Check(long)
方法(第 7.5.3.2 节),因为参数的类型是 int
,并且恒等式转换比扩大转换“更好”(第 7.5.3.3 节)。
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 has a type S and an identity conversion exists from S to T1 but not from S to T2
- ...
这里E
是int
,T1
是int
,T2
是long
。存在从 int
到 int
的身份转换,但不是从 int
到 long
... 因此适用此规则,并且从 int
到 int
优于从 int
到 long
.