【发布时间】:2015-09-09 09:49:13
【问题描述】:
场景:有一个字符串常量列表(现在超过 100 个,将来会更多),定义如下:
public const string ChildA = "Child A";
public const string ChildASomeParameter = "Some parameter";
public const string ChildASomeOtherParameter = "Some other parameter";
...
public const string ChildB = "Child B";
public const string ChildBSomeParameter = "Some different parameter";
public const string ChildBSomeOtherParameter = "Some parameter"; // values are not unique
...
问题:将它与智能感知一起使用并不好:当需要ChildA 时,您可能会得到智能感知提供ChildASomeParameter99999。滚动该名称或完全输入名称显然效率不高。
我想将参数移动到嵌套类型中,像这样
public const string ChildA = "Child A";
public class ChildA
{
public const string SomeParameter1 = "Some parameter 1";
public const string SomeParameter2 = "Some parameter 2";
}
但是还有一个编译时间问题:
“MyConstants”类型已经包含“ChildA”的定义
我需要有关如何处理该问题的帮助(想法)。
我的想法:
- 将
ChildA放入另一个嵌套类型?这将增加开销:ChildA的使用频率将比它的任何参数更频繁,using static在这里非常出色,必须输入类似Childs.ChildA的内容并不快。 - 重命名?将
ChildA重命名为丑陋的_ChildA?或者将嵌套类型重命名为丑陋的东西?那么什么名字不丑呢?
也许有人知道更好的方法?
【问题讨论】:
-
例如公共类 ChildA { public const string Name = "ChildA"; }
-
@bushed,这听起来是迄今为止最好的选择。我仍然希望有更好的选择(我不知道或没有想到的)。
-
如果常量不能被分离并与特定的类相关联,并且实际上只是通用常量(即错误代码列表或类似的东西),我很可能会接受打击,并且接受将涉及打字。它们显然属于一起,所以应该在一起,并且至少名称是明确而简洁的,即使打字不愉快。要么这样,要么为常量的重复部分提供适当的缩写。
-
显然 nameof() 被认为是编译时常量。例如。可以放在属性里。如果您可以只使用属性名称而不是字符串,它可能会解决问题 public class A : Attribute { public A(string name) { } public const string Name = nameof(Name); } [A(nameof(A.Name))] 公共类 X { }
-
你有性能方面的考虑吗?
标签: c# .net constants intellisense