我正在寻找与 Java 的 final
等效的 C#。它存在吗?
C#有没有类似下面的东西:
public Foo(final int bar);
在上面的例子中,bar
是一个只读变量,不能被 Foo()
改变。有没有办法在 C# 中执行此操作?
例如,也许我有一个很长的方法可以处理某些对象的 x
、y
和 z
坐标(整数).我想绝对确定该函数不会以任何方式改变这些值,从而破坏数据。因此,我想将它们声明为只读。
public Foo(int x, int y, int z) {
// do stuff
x++; // oops. This corrupts the data. Can this be caught at compile time?
// do more stuff, assuming x is still the original value.
}
最佳答案
不幸的是,您不能在 C# 中执行此操作。
const
关键字只能用于局部变量和字段。
readonly
关键字只能用于字段。
NOTE: The Java language also supports having final parameters to a method. This functionality is non-existent in C#.
来自 http://www.25hoursaday.com/CsharpVsJava.html
编辑(2019/08/13):
我把它扔进去是为了提高可见性,因为它已被接受并且在列表中名列前茅。现在可以使用 in
参数。参见 the answer下面是详细信息。
关于c# - 参数可以是常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2339074/