在c#中,什么相当于Java的final ?
当前回答
Java类final和方法final ->密封。 Java成员变量final -> readonly为运行时常量,const为编译时常量。
没有等价的局部变量final和方法参数final
其他回答
如前所述,对于方法和类来说,sealed相当于final。
至于其他的,就很复杂了。
For static final fields, static readonly is the closest thing possible. It allows you to initialize the static field in a static constructor, which is fairly similar to static initializer in Java. This applies both to constants (primitives and immutable objects) and constant references to mutable objects. The const modifier is fairly similar for constants, but you can't set them in a static constructor. On a field that shouldn't be reassigned once it leaves the constructor, readonly can be used. It is not equal though - final requires exactly one assignment even in constructor or initializer. There is no C# equivalent for a final local variable that I know of. If you are wondering why would anyone need it: You can declare a variable prior to an if-else, switch-case or so. By declaring it final, you enforce that it is assigned at most once. Java local variables in general are required to be assigned at least once before they are read. Unless the branch jumps out before value read, a final variable is assigned exactly once. All of this is checked compile-time. This requires well behaved code with less margin for an error.
综上所述,c#没有final的直接对等物。虽然Java缺少c#的一些不错的特性,但作为一个Java程序员,看到c#在哪些方面没有提供相应的特性,让我感到耳目一新。
这里的每个人都缺少的是Java对最终成员变量的明确赋值的保证。
对于具有最终成员变量V的类C,通过C的每个构造函数的每一个可能的执行路径都必须精确地赋值V一次-未能赋值V或赋值V两次或两次以上将导致错误。
c#的readonly关键字就没有这样的保证——编译器很乐意保留未分配的readonly成员,或者允许你在构造函数中多次分配它们。
因此,final和readonly(至少对于成员变量而言)肯定是不相等的——final要严格得多。
Java类final和方法final ->密封。 Java成员变量final -> readonly为运行时常量,const为编译时常量。
没有等价的局部变量final和方法参数final
http://en.csharp-online.net/CSharp_FAQ:_What_are_the_differences_between_CSharp_and_Java_constant_declarations
c#常量使用const关键字声明编译时常量,使用readonly关键字声明运行时常量。在c#和Java语言中,常量的语义是相同的。
推荐文章
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?
- 如何使用try catch进行异常处理是最佳实践
- 替换字符串中第一次出现的模式
- .NET中字节的字面后缀?
- 如何处理AccessViolationException
- c#忽略证书错误?