【问题标题】:How to limit scope of a constant to method/block如何将常量的范围限制为方法/块
【发布时间】:2014-04-24 20:28:35
【问题描述】:

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

类似于以下内容:

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

【问题讨论】:

  • 你为什么要那个? return a + 10 有什么问题?
  • 是什么让你认为“显然它不存在?”
  • // obviously this doesn't exist 我很确定它完全可以
  • @Selman22 想象在您的方法/块中多次使用该值。如果你需要改变某些东西,你不会想改变它的每一次使用。
  • 以上cmets都对,请问之前有试过吗?如果你没有,你应该

标签: c# scope constants


【解决方案1】:

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

你写的时候

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

    return a + SomeCompileTimeConstant;
}

你错了。

【讨论】:

  • "你可以在函数中声明一个常量。" - C# 没有函数。它有方法 ;p 但基本上,+1
猜你喜欢
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
相关资源
最近更新 更多