c# - 为什么我可以将 1 作为 short 而不是 int 变量 i 传递?

标签 c# compiler-errors int type-conversion implicit-conversion

为什么第一次和第二次 Write 有效但最后一次无效?有没有办法允许所有 3 个并检测它是 1、(int)1 还是我传入?真的为什么允许一个但最后一个?第二次被允许但不是最后一次真的让我大吃一惊。

Demo to show compile error

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 type sbyte, byte, short, ushort, uint, or ulong, 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 type ulong, 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/

相关文章:

c# - COM 对象上的扩展方法不好吗?

c# - 如何在C#中复制列表

c# - 如何解决此 .Net 3.5 警告/错误?

java - 找到一个非零整数 x 其中 x == -x?

c# - 在 C# 中定位安装程序路径

c# - 重新激活时Windows Phone中的界面刷新

python - 导入tensorflow时出现错误 'ImportError: DLL load failed: The specified module could not be found.'

css - Mediawiki - 脚本错误 : Lua error at line 1: unexpected symbol near '/'

java - Java中的用户输入字符串和整数

java - 负字符值 JAVA