问题描述
为什么第一个和第二个 Write 可以工作,而最后一个不行?有没有一种方法可以允许所有 3 个并检测它是 1、(int)1 还是我传入的?真的为什么允许一个但最后一个?第二个被允许但不是最后一个真的让我大吃一惊.
Why does the first and second Write work but not the last? Is there a way I can allow all 3 of them and detect if it was 1, (int)1 or i passed in? And really why is one allowed but the last? The second being allowed but not the last really blows my mind.
演示编译错误
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!?
}
}
推荐答案
前两个是常量表达式,最后一个不是.
The first two are constant expressions, the last one isn't.
C# 规范允许将常量从 int 隐式转换为 short,但不允许其他表达式.这是一个合理的规则,因为对于常量,编译器可以确保值适合目标类型,但对于普通表达式则不能.
The C# specification allows an implicit conversion from int to short for constants, but not for other expressions. This is a reasonable rule, since for constants the compiler can ensure that the value fits into the target type, but it can't for normal expressions.
这条规则符合隐式转换应该是无损的准则.
This rule is in line with the guideline that implicit conversions should be lossless.
6.1.8 隐式常量表达式转换
隐式常量表达式转换允许以下转换:
An implicit constant expression conversion permits the following conversions:
int
类型的 constant-expression(第 7.18 节)可以转换为sbyte
、byte
类型、short
、ushort
、uint
或ulong
,提供 constant-expression<的值/em> 在目标类型的范围内.- 只要 constant-expression 不是负数.
- 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 版)
(Quoted from C# Language Specification Version 3.0)
这篇关于为什么我可以将 1 作为短变量传递,而不是 int 变量 i?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!