开发者

Dot notation for hierarchical related string values

I have a lot of constant string values in my applicatio开发者_运维问答n which I want to have as strongly typed objects in C# for code reuse and readability. I would like to be able to reference the string value like so:

Category.MyCategory  //returns a string value ie “My Category”
Category.MyCategory.Type.Private //returns a string value ie “private”
Category.MyCategory.Type.Shared //returns a string value ie “shared”

I have started by implementing the following classes each containing a list of public string valued fields with a public property which exposes the child.

Category, MyCategory, Type

However I already know this is not the way to go so could do with a bit of advice on this one.

An example of this is where I am using the Syndication classes to add a category to an atom feed. I am creating the items in this feed dynamically so need to use the notation as shown.

item.Categories.Add( new SyndicationCategory
                 {
                     Scheme = Category.PersonType, 
                     Label="My Category",
                     Name=Category.MyCategory.Type.Private  
                 });


Keep your string constants close to where you need them, IMO having a class that just declares constants is an OO antipattern


Why not simply implement them as classes with overridden ToString implementations?

public class MyCategory
{
    private readonly MyType type;

    public MyCategory()
    {
        this.type = new MyType();
    }

    public MyType Type
    {
        get { return this.type; }
    }

    // etc.

    public override string ToString()
    {
        return "My Category";
    }
}

public class MyType
{
    public override string ToString()
    {
        return "My Type";
    }

    // more properties here...
}

However, for general purposes, consider whether the strings in themselves don't represent concepts that are better modeled as full-blown objects.


I completely agree with Rob. If you still want to have a "bag of strings", you could try using nested classes, something like below. I don't really like it, but it works.

public class Category 
{
    public class MyCategory 
    {
        public const string Name = "My Category";

        public class Type
        {
            public const string Private = "private";
            public const string Shared = "shared";
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜