c# - 参数可以是常量吗?

标签 c# constants readonly parameter-passing

我正在寻找与 Java 的 final 等效的 C#。它存在吗?

C#有没有类似下面的东西:

public Foo(final int bar);

在上面的例子中,bar 是一个只读变量,不能被 Foo() 改变。有没有办法在 C# 中执行此操作?

例如,也许我有一个很长的方法可以处理某些对象的 xyz 坐标(整数).我想绝对确定该函数不会以任何方式改变这些值,从而破坏数据。因此,我想将它们声明为只读。

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/

相关文章:

c# - KeyVaultClient.AuthenticationCallback Delegate 的参数来自哪里?

c# - SortedDictionary 抛出带有两个不同条目的 "same key already exists"

c++ - 这个语句 "auto iter = first"发生了什么

c# - 使用NUnit测试属性为只读

c# - 有没有办法让抽象类中的静态只读字段在派生类中实例化?

c# - 如何在从构造函数调用的初始化方法中设置只读字段?

c# - 在 Xaml 中声明元组

c# - Windows 手机 : How to stay in the Current page rather than navigating to another page?

c++ - 准备和执行 QSqlQuery 会改变执行它的方法的逻辑常量吗?

c - 来自 const 的无效转换,但未声明为 const