我可以在声明中重复一个常量字符串吗?

时间:2013-09-08 14:58:54

标签: c# string c-preprocessor const

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

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);
...

是否有一些预处理程序指令或其他一些实现此目的的方法?

P.S。 我已经知道const string tabLevel2 = tabLevel1 + tabLevel1;工作,可能是由于this。我正在寻找任意n的一般情况。

修改

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

3 个答案:

答案 0 :(得分:2)

你不能在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);

希望它有所帮助。

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:0)

你可以这样做

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