C# 具有多个常量的智能感知(嵌套?)
场景:有一个字符串常量列表(现在超过100个,将来还会更多),定义如下:C# 具有多个常量的智能感知(嵌套?),c#,.net,constants,intellisense,C#,.net,Constants,Intellisense,场景:有一个字符串常量列表(现在超过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 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
...
问题:将此功能与intellisense配合使用不太好:当需要ChildA
时,您可能会得到intellisense产品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
在这里非常有用,必须键入类似于使用static
速度不快Childs的内容。ChildA
- 改名?将
重命名为丑陋的ChildA
?或者将嵌套类型重命名为丑陋的类型?那什么名字不难看呢\u ChildA
namespace N1 // N1
{
class C1 // N1.C1
{
class C2 // N1.C1.C2
{
}
}
namespace N2 // N1.N2
{
class C2 // N1.N2.C2
{
}
}
}
对当前类使用
Current
如何
static void Main(string[] args)
{
System.Console.WriteLine(Constants.ChildA.Current);
System.Console.WriteLine(Constants.ChildB.SomeOtherParameter);
System.Console.WriteLine(Constants.ChildA.SomeParameter);
}
public static class Constants
{
public static class ChildA
{
public const string Current = "Child A";
public const string SomeParameter = "Some parameter";
public const string SomeOtherParameter = "Some other parameter";
}
public static class ChildB
{
public const string Current = "Child B";
public const string SomeParameter = "Some different parameter";
public const string SomeOtherParameter = "Some parameter";
}
}
备选案文1:
public class ChildA
{
public const string Name = "Child A"
public const string SomeParameter1 = "Some parameter 1";
public const string SomeParameter2 = "Some parameter 2";
}
选项2(带约束):
用法:nameof(ChildA),nameof(ChildA.SomeParameter1)
要详细说明制约因素:
- 不能使用任意字符串
只返回顶级名称。例如,nameof
nameof(ChildA.ChildAA.Param1)=“Param1”
ChildA
和ChildASomeParameter
?我的意思是名称空间使使用相同类型的名称变得容易,但是@dotcor是更好的主意。使用静态常量
使其更加完善(与简单的常量列表相比)。避免使用当前的会很酷,但可能没有办法。我们可以使用“enum”而不是选项2。问题是(ChildA)的名称是什么“Child A”
(注意空格),实际上有一些值,如“Some property(A)”
(包含不能用作成员名称的字符)。@Chandru您的意思是不是用常量字符串代替常量字符串-这将限制进一步嵌套-您不能在enums@Chandru,使用字符串枚举?不,我们不能。我的意思是这样代替选项2 public enum ChildA{ChildA,SomeParameter1,SomeParameter2}无论如何,我们不能使用这个选项,因为我们需要单词之间的空格。
public class ChildA
{
public const string SomeParameter1 = nameof(SomeParameter1);
public const string SomeParameter2 = nameof(SomeParameter2);
}