为什么第一次和第二次 Write 有效但最后一次无效?有没有办法允许所有 3 个并检测它是 1、(int)1 还是我传入?真的为什么允许一个但最后一个?第二次被允许但不是最后一次真的让我大吃一惊。
using System;
class Program
{
public static void Write(short v) { }
static void Main(string[] args)
{
Write(1);//ok
Write((int)1);//ok
int i=1;
Write(i);//error!?
}
}
最佳答案
前两个是常量表达式,最后一个不是。
C# 规范允许对常量进行从 int 到 short 的隐式转换,但不允许对其他表达式进行隐式转换。这是一个合理的规则,因为对于常量,编译器可以确保该值适合目标类型,但不能用于普通表达式。
这个规则符合隐式转换应该是无损的准则。
6.1.8 Implicit constant expression conversions
An implicit constant expression conversion permits the following conversions:
- A constant-expression (§7.18) of type
int
can be converted to typesbyte
,byte
,short
,ushort
,uint
, orulong
, provided the value of the constant-expression is within the range of the destination type.- A constant-expression of type
long
can be converted to typeulong
, provided the value of the constant-expression is not negative.
(引自C#语言规范3.0版)
关于c# - 为什么我可以将 1 作为 short 而不是 int 变量 i 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11432508/