为什么C#不允许常量和静态在同一行? [英] Why does C# not allow const and static on the same line?

查看:142
本文介绍了为什么C#不允许常量和静态在同一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么C#不允许常量和静态在同一行?在Java中,必须声明一个字段作为静态和最终作为一个常数。为什么C#不会让你声明常量作为最后?

Why does C# not allow const and static on the same line? In Java, you must declare a field as 'static' and 'final' to act as a constant. Why does C# not let you declare const's as final?

我做进一步的区分,在Java中,每个接口是公开的,抽象​​的,这是否是显式声明的或没有。不是常量在自然界有效静态的?为什么在这个的确C#放水?

I make the further distinction that in Java, every interface is public and abstract, whether this is explicitly declared or not. Aren't const's effectively static in nature? WHy does C# balk at this?

推荐答案

常量静态真就意味着不同的事情,不同的存储机制,不同的初始化。 静态读/写,因此必须分配的内存进行存储,并且必须在运行时初始化。 A 静态可以用一个字面值或表达式进行初始化。相反,常量是不可改变的,必须用的编译时间常数被初始化的(通常是文本值,或者可以在编译时完全计算的表达式)。的值是在编译时,因此它可以直接在所生成的代码嵌入公知的,因此不需要在运行时被分配的存储

const and static really do mean different things, different storage mechanism, different initialisation. static is read/write, therefore must have memory allocated for storage and must be initialised at runtime. A static can be initialised with a literal value or an expression. In contrast, a const is immutable and must be initialised with a compile time constant (typically a literal value, or an expression that can be fully evaluated at compile time). The value is known at compile time so it can be embedded directly in the generated code, therefore requires no storage to be allocated at runtime.

这篇关于为什么C#不允许常量和静态在同一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆