【问题标题】:Can I repeat a constant strings at declaration?我可以在声明时重复一个常量字符串吗?
【发布时间】:2013-09-08 14:58:53
【问题描述】:

我有一组相互关联的常量字符串:

private const string tabLevel1 = "\t";
private const string tabLevel2 = "\t\t";
private const string tabLevel3 = "\t\t\t";
...

我正在寻找一种更优雅的方式来声明这些,例如:

private const string tabLevel1 = "\t";
private const string tabLevel2 = REPEAT_STRING(tabLevel1, 2);
private const string tabLevel3 = REPEAT_STRING(tabLevel1, 3);
...

是否有一些预处理指令或其他方式来实现这一点?

附: 我已经知道const string tabLevel2 = tabLevel1 + tabLevel1; 有效,可能是由于this。我正在寻找任意n 的一般情况。

编辑

我想澄清为什么我需要const 而不是static readonly:常量用作属性装饰器的参数,例如[GridCategory(tabLevel2)],并且必须在编译时知道。

【问题讨论】:

  • 您希望它重复多少次?我认为关心并不重要。 常量是你应该感到满意的东西,即使你必须输入数百行来声明它们Win32 Constants 就是一个例子。

标签: c# string c-preprocessor constants


【解决方案1】:

你不能在 C# 中做到这一点。在 c# 中也没有像 c 或 c++ 那样的宏预处理器。最好的办法是使用以下内容:

private const string tabLevel1 = "\t";
private static readonly string tabLevel2 = new string('\t',2);
private static readonly string tabLevel3 = new string('\t',3);

希望对你有帮助。

【讨论】:

  • 谢谢,但正如 Magnus 所说 - 您的代码无法编译。您不能调用方法(即使是静态方法),也不能将new 运算符用于const。该值必须在编译时知道。
【解决方案2】:

因为您需要在属性定义中使用常量,并且因为所有常量都必须能够在编译时进行评估,所以您可以做的最好的事情是使用字符串文字或涉及其他常量和字符串文字的表达式。另一种选择是提供属性的另一种实现,它采用的不是制表符级别的字符串表示,而是它的数值,可能还有制表符。

 public class ExtendedGridCategoryAttribute : GridAttribute
 {
      public ExtendedGridCategoryAttribute(int level, char tabCharacter)
          : base(new string(tabCharacter, level))
      {
      }
 }

 [ExtendedGridCategory(2,'\t')]
 public string Foo { get; set; }

【讨论】:

  • 由于子类属性的巧妙想法而被接受:)
【解决方案3】:

你可以这样做

private const int tabCount = 10;
private string[] tabs = new string[tabCount];
void SetTabs()
{
  string tab = "";
  for(int x = 0; x<=tabCount - 1; x++)
  {
    tab += "\t";
    tabs[x] = tab;
  }
}

【讨论】:

    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2021-09-26
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    相关资源
    最近更新 更多