如何在 C# 中声明局部常量?

发布于 2024-08-17 20:12:38 字数 262 浏览 6 评论 0原文

如何在 C# 中声明局部常量?

就像在 Java 中一样,您可以执行以下操作:

public void f(){
  final int n = getNum(); // n declared constant
}

如何在 C# 中执行相同的操作?我尝试使用 readonlyconst 但似乎都不起作用。

任何帮助将不胜感激。

谢谢。

How to declare a local constant in C# ?

Like in Java, you can do the following :

public void f(){
  final int n = getNum(); // n declared constant
}

How to do the same in C# ? I tried with readonly and const but none seems to work.

Any help would be greatly appreciated.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

思念满溢 2024-08-24 20:12:38

在 C# 中,您无法创建从方法中检索的常量。

编辑:死链接
http://msdn.microsoft.com/en -us/library/e6w8fe1b(VS.71).aspx

这个文档应该有帮助:
https://learn.microsoft.com/en-us /dotnet/csharp/语言参考/关键字/const

常量表达式是可以在以下位置完全求值的表达式:
编译时间。

In C#, you cannot create a constant that is retrieved from a method.

Edit: dead link
http://msdn.microsoft.com/en-us/library/e6w8fe1b(VS.71).aspx

This doc should help:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const

A constant expression is an expression that can be fully evaluated at
compile time.

蓦然回首 2024-08-24 20:12:38

将局部变量声明为迭代变量。迭代变量是只读的
(你没有要求一个漂亮的解决方案)。

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'"
  }
}

Declare your local variable as an iteration variable. Iteration variables are readonly
(You didn't ask for a pretty solution).

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'"
  }
}
执笏见 2024-08-24 20:12:38

我不确定为什么 readonlyconst 不适合您,因为这些是您需要的关键字。如果您有文字(数组文字除外),则使用 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 字段可以是静态的或实例的。

I'm not sure why readonly and const didn't work for you since these are the keywords you need. You use const if you have a literal (except for array literals) and readonly otherwise:

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 only works on class level (that is, you can only apply it to fields). Also as a consequence of const requiring a literal, it's inherently static while a readonly field can be either static or instance.

狼性发作 2024-08-24 20:12:38

截至 2018 年 10 月 2 日,c# 中不可能有只读本地,但有一个开放的 针对该功能的提案,该功能正在进行讨论。

这篇文章提供了有用的摘要。

As of 2018-10-02, it isn't possible to have a readonly local in c#, but there is an open proposal for that feature that has ongoing discussion.

This article provides a useful summary.

屋顶上的小猫咪 2024-08-24 20:12:38

有一种解决方法需要 ReSharper。你无法获得只读的本地变量,但你至少可以检测突变的本地变量并为它们涂上不同的颜色。

使用字体和颜色项Resharper 可变局部变量标识符

对我来说,我将本地颜色设置为灰色,然后我为突变变量选择了粗体白色(这是一个深色主题)。这意味着任何被写入多次的变量与常规变量相比都会显示得更亮。然后,您可以尽力避免出现变异变量,或者如果该方法确实需要一个变量,那么它至少会被突出显示。

There is a sort of workaround that requires ReSharper. You can't get readonly locals, but you can at least detect mutated ones and color them differently.

Use the Fonts and Colors item Resharper Mutable Local Variable Identifier.

For me, I have locals colored grey, and then I chose a bold white for the mutated variables (this is with a dark theme). This means that any variable that is written to more than once shows up bright compared to regular ones. You can then do what you can to try to avoid having a mutated variable, or if the method really does require one then it will at least be highlighted.

心欲静而疯不止 2024-08-24 20:12:38

在您提供的示例中,您需要将变量声明为static,因为您正在使用方法调用来初始化它。如果您使用常量值(例如 42)进行初始化,则可以使用 const。对于类、结构和数组,readonly 应该可以工作。

In the example you gave, you need to declare the variable as static, because you're initializing it with a method call. If you were initializing with a constant value, like 42, you can use const. For classes, structs and arrays, readonly should work.

陈年往事 2024-08-24 20:12:38

const关键字用于修改
字段或局部的声明
变量。

来自 MSDN

由于 C# 无论如何都无法强制执行“const Correctnes”(如 c++),所以我认为它不是很有用。由于职能范围非常狭窄,因此很容易不失去监督。

The const keyword is used to modify a
declaration of a field or local
variable.

From MSDN.

Since C# can't enforce "const correctnes" (like c++) anyway, I don't think it's very useful. Since functions are very narrwoly scoped, it is easy not to lose oversight.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文