2017-01-24 66 views
-1

我正在使用在线转换工具将VB代码转换为C#。 VB的代码是:Can Convert.ToDecimal可以返回一个常量吗?

Private Const constant1 As Decimal = CDec(37.5) 

结果:

private const decimal constant1 = Convert.ToDecimal(37.5); 

然而,编译时的错误消息:

表达被分配给 '常量1' 必须是恒定的

为了消除错误,我修改了代码:

private const decimal constant1 = (decimal)37.5; 

有谁能告诉为什么Convert.ToDecimal无法返回常量吗?

+2

,因为回报率取决于值被转换 – Plutonix

+0

参考数字后缀:http://stackoverflow.com/questions/3569695/c-sharp-numeric-suffixes – GSP

回答

4

这里你不需要Convert.ToDecimal(或CDec),如果你自己转换的值是不变的。

你可以简单的写:

private const decimal constant1 = 37.5m; 
1

没有,方法的返回值是不兼容const(因为他们是,嗯,不是恒定的,至少不是编译器)。但是你可以摆脱功能和使用十进制文字(“M”后缀)(和投地!):

private const decimal constant1 = 37.5m; 
2

当常量编译时,实际值存储在程序集的元数据。这意味着它在运行时完全不能改变。实际上,消费程序集假定它永远不会改变,并将值编译到它们的元数据中。

当您使用Convert.ToDecimal()时,您正在执行运行时代码。因此,无法将该值分配给该常量,因为在将值编译为程序集时无法运行代码(至少不是没有编译器黑客)。

正如@AlexD所提到的,如果您使用静态只读值,您可以在运行时对其进行设置,因为它没有被编译到程序集中。

private static readonly decimal constant1 = Convert.ToDecimal(36.6); 
相关问题