2014-11-22 41 views
0

使用C#;我刚刚意识到,宣布noValueNumberconst int并从此short函数返回它。
为什么没有一个错误信息,如:为什么没有必要为此C#函数强制转换?

Can't convert exxpression type int to return type short

public static short ValueFromString(string onlyNumbersString) 
    { 
     if (onlyNumbersString.Length == 0) 
     { 
      const int noValueNumber = 999; 

      return noValueNumber; // ¿...? 
     } 

     return Int16.Parse(onlyNumbersString); 
    } 

不应该是必要的铸造?还是有,但隐藏?

回答

3

MSDN提到:

You cannot implicitly convert nonliteral numeric types of larger storage size to short [...]

A(常数)值,适合short虽然是与隐式转换确定。

编辑:发现你的榜样,Implicit Numeric Conversions Table (C# Reference),指出正确的(积极)的文档:

A constant expression of type int can be converted to sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant expression is within the range of the destination type.

1

这是因为编译器足够聪明地看到,999是正确的short值,它是const,所以它不会被改变(的noValueNumber使用可以实际上是由这个值简单替换)。如果你会尝试例如返回40000你会得到一个编译错误:

Constant value '40000' cannot be converted to a 'short'

在其他的方式,如果你删除const你会得到预期:

Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

再换句话说,如果你反编译你的一部开拓创新的功能,您可以:

public static short ValueFromString(string onlyNumbersString) 
{ 
    short result; 
    if (onlyNumbersString.Length == 0) 
    { 
     result = 999; 
    } 
    else 
    { 
     result = short.Parse(onlyNumbersString); 
    } 
    return result; 
} 

这是编译器如何“看”这个代码,你看,有没有const int这里的。

+0

我明白了。声明一个'const',只是为了向你展示问题中返回值类型的明确性。 – Shin 2014-11-22 12:42:15

0

我想说这是因为您已将变量定义为a constant,其值为999(这是一个有效的Int16值),因此可以轻松地使用该值。如果您从定义中删除const,它将停止工作。智能编译器:)

0

999是一个有效的short号码。由于您使用的是const int noValueNumberconst是此处的关键字),因此使用名称noValueNumber作为999的别名。在预编译处理期间,noValueNumber的每次出现都被替换为999,因此编译的代码实际上是return 999;

相关问题