开发者

What is the best "place" to hold read-only structured data?

I am holding structured read only data in enum type, now I would like to extend structure and for every value in enum add additional fields. So, my original enum is:

public enum OutputFormats { Pdf, Jpg, Png, Tiff, Ps };

and I want to extend them like so:

Value=Pdf
FileName="*.PDF"
ID=1

Value=Jpg
FileName="*.jpg"
ID=2

...and so on开发者_StackOverflow中文版.

An enum can't hold a multidimensional data structure, so what is generally considered the best "place" to hold such structured data? Should I create a class with value, filename, and id properties and initialize the data in the class constructor?


Perhaps this pseudo-enum pattern will be useful:

public class OutputFormats
{
    public readonly string Value;
    public readonly string Filename;
    public readonly int ID;

    private OutputFormats(string value, string filename, int id)
    {
        this.Value = value;
        this.Filename = filename;
        this.ID = id;
    }

    public static readonly OutputFormats Pdf = new OutputFormats("Pdf", "*.PDF", 1);
    public static readonly OutputFormats Jpg = new OutputFormats("Jpg", "*.JPG", 2);
}

Another variation, perhaps more concise:

public class OutputFormats
{
    public string Value { get; private set; }
    public string Filename { get; private set; }
    public int ID { get; private set; }

    private OutputFormats() { }

    public static readonly OutputFormats Pdf = new OutputFormats() { Value = "Pdf", Filename  = "*.PDF", ID = 1 };
    public static readonly OutputFormats Jpg = new OutputFormats() { Value = "Jpg", Filename = "*.JPG", ID = 2 };
}


Yes, create a class OutputFormat with Value, Filename and ID properties. You could store the data in an XML file and parse the XML file to a List, or you could initialize the OutputFormat objects somewhere in the code.


Create a class or struct with readonly properties and fields like this:

 struct OutputFormat
 {
      public int Id { get; private set; }
      public OutputFormats Format { get; private set; }
      public string Filename { get; private set; }

      public OutputFormat(int id, OutputFormats format, string filename)
      {
          Id = id;
          Format = format; 
          Filename = filename;
      }
 }


// using a string key makes it easier to extend with new format.
public interface IOutputRepository
{
    //return null if the format was not found
    Output Get(string name);
}

// fetch a format using a static class with const strings.
var output = repository.Get(OutputFormats.Pdf);


I would look into using a struct for this I think. They are ideal for data like this that will not be changed once created.

http://msdn.microsoft.com/en-us/library/ah19swz4(v=vs.71).aspx

Andrew

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜