C# 如何将常数的范围限制为方法/块

C# 如何将常数的范围限制为方法/块,c#,scope,constants,C#,Scope,Constants,有没有办法将编译时常量的范围限制为一个方法/代码块,以避免对值进行硬编码 如下所示: public int SomeMethod(int a) { const int SomeCompileTimeConstant = 10; // obviously this doesn't exist return a + SomeCompileTimeConstant; } 与硬编码值相反: public int SomeMethod(int a) {

有没有办法将编译时常量的范围限制为一个方法/代码块,以避免对值进行硬编码

如下所示:

public int SomeMethod(int a) {
    const int SomeCompileTimeConstant = 10; // obviously this doesn't exist

    return a + SomeCompileTimeConstant;
}
与硬编码值相反:

public int SomeMethod(int a) {              
    return a + 10;
}
或者将其设置为类级别常量:

public class A {
    private const int SomeCompileTimeConstant = 10;

    public int SomeMethod(int a) {
        return a + SomeCompileTimeConstant;
    }
}

您可以在函数中声明一个常量

当你写信的时候

public int SomeMethod(int a) {
    const int SomeCompileTimeConstant = 10; // obviously this doesn't exist

    return a + SomeCompileTimeConstant;
}

你错了。

你为什么要这样?
返回+10有什么问题?是什么让你认为“显然它不存在?”
//显然它不存在
我完全肯定它存在does@Selman22想象一下在方法/块中多次使用该值。如果你需要改变一些东西,你不会想改变它的每一个用法。上面的评论是正确的,你在问之前试过吗?如果你没有,你应该“你可以在一个函数中声明一个常数。”-C#没有函数。它有方法;但基本上是+1