如何在C#中声明本地常量?
与Java类似,您可以执行以下操作:
public void f(){
final int n = getNum(); // n declared constant
}
如何在C#中实现相同的功能?我尝试使用readonly
和const
,但似乎都不起作用。
任何帮助将不胜感激。
谢谢。
如何在C#中声明本地常量?
与Java类似,您可以执行以下操作:
public void f(){
final int n = getNum(); // n declared constant
}
如何在C#中实现相同的功能?我尝试使用readonly
和const
,但似乎都不起作用。
任何帮助将不胜感激。
谢谢。
常量表达式是一种可以在编译时完全评估的表达式。
final
和const
有不同的含义。在C#中,const
值必须在编译时就已知。真正的问题是C#不支持局部的readonly
变量,这很遗憾,因为它们会很方便。 - Nickvar readonly id = GetId();
或 var const id = -1;
,后者基本上是一个文本,它会被其值所替代。 - Paul-Sebastian Manole将你的本地变量声明为迭代变量。迭代变量是只读的。(你没有要求一个漂亮的解决方案)。
public void f()
{
foreach (int n in new int[] { getNum() }) // n declared constant
{
n = 3; // won't compile: "error CS1656: Cannot assign to 'n' because it is a 'foreach iteration variable'"
}
}
var index=GetNum()
更改为foreach
以强制编译器检查我的代码。 - Sergey.quixoticaxis.Ivanov我不确定为什么readonly
和const
对你没起作用,因为这些是你需要的关键词。如果你有一个字面量(除了数组字面量),则使用const
,否则,请使用readonly
:
public void f()
{
const int answer = 42;
}
private readonly int[] array = new int[] { 1, 2, 3, 4 };
private readonly DateTime date = DateTime.Now;
public void g()
{
Console.WriteLine(date.ToString());
}
readonly
只适用于类级别(也就是只能应用于字段)。另外,由于 const
需要一个字面量,它本质上是静态的,而 readonly
字段可以是静态的或实例的。
有一种解决方法需要使用ReSharper。您无法获得只读本地变量,但是您至少可以检测到已经变异的变量并将它们以不同的颜色显示。
使用“字体和颜色”项Resharper Mutable Local Variable Identifier。
对于我来说,本地变量会被涂成灰色,而我选择了加粗的白色来表示已经变异的变量(这适用于暗色主题)。这意味着任何写入超过一次的变量显示为亮色与普通变量相比。然后您可以尽可能避免变异变量,如果该方法确实需要一个则它至少会被突出显示。
int x = 5; x = 3;
这样的内容,x 应该会改变颜色。我想这可能是版本问题,是的。 - Dave Cousineaustatic
,因为你正在使用方法调用进行初始化。如果你使用常量值(如42)进行初始化,则可以使用const
。对于类、结构体和数组,readonly
应该可以工作。const
。对于参数、返回值、局部变量,所有可以声明为const的都声明为const。 - Martin