如何将常量的范围限制为方法/块

时间:2014-04-24 20:28:36

标签: c# scope const

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

如下所示:

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;
    }
}

1 个答案:

答案 0 :(得分:3)

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

当你写

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

    return a + SomeCompileTimeConstant;
}

你错了。

相关问题