Using nested classes for constants?
What's wrong with using nested classes to group constants?
Like so:
public static class Constants
{
public static class CategoryA
{
public const string ValueX = "CatA_X";
public const string ValueY = "CatA_Y";
}
public static class CategoryB
{
public const string ValueX = "CatB_X";
public const string ValueY = "CatB_Y";
}
}
Used like so:
Console.WriteLi开发者_如何学JAVAne(Constants.CategoryA.ValueY);
Console.WriteLine(Constants.CategoryB.ValueX);
You could also make the "Constants"-class partial...
There is some guideline (updated for fx 4.5) against public nested classes:
√ DO use nested types when the relationship between the nested type and its outer type is such that member-accessibility semantics are desirable.
X AVOID publicly exposed nested types. The only exception to this is if variables of the nested type need to be declared only in rare scenarios such as subclassing or other advanced customization scenarios.
X DO NOT use nested types if the type is likely to be referenced outside of the containing type.
I think your example matches the first point (ie: you're good).
Who said it was wrong? Constants can be (and are) defined anywhere in a class hierarchy.
Not saying that what you did is wrong, but what about using namespaces instead like this:
namespace Constants
{
public static class CategoryA
{
public const string ValueX = "CatA_X";
public const string ValueY = "CatA_Y";
}
public static class CategoryB
{
public const string ValueX = "CatB_X";
public const string ValueY = "CatB_Y";
}
}
精彩评论