什么是存储只读结构化数据的最佳“位置”?

4

我可以帮助您进行翻译。以下是需要翻译的内容:

我在枚举类型中持有结构化只读数据,现在我想扩展结构,并为枚举中的每个值添加附加字段。因此,我的原始枚举如下:

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

我希望你能帮我扩展它们,就像这样:
Value=Pdf
FileName="*.PDF"
ID=1

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

枚举无法保存多维数据结构,那么一般认为保存这种结构化数据的最佳方式是什么呢?我应该创建一个类,拥有valuefilenameid属性,并在类的构造函数中初始化数据吗?


是的,这种类型的事情通常使用类来完成。除非您需要实例具有值类型语义,否则使用结构没有特别的优势。 - Cody Gray
这听起来太模糊了。当然,类或结构体都可以使用,如果除了数据只读之外没有任何约束/要求,则两者都可以。 - K Mehta
5个回答

3
也许这个伪枚举模式会有所帮助:
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);
}

另一种可能更为简洁的变体:

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 };
}

抱歉,您的值初始化代码存在错误,无法编译。 - Tomas
@Tomas - 对不起,我应该说这是脑编译的代码。你应该能够自己解决语法错误,对吧? - Vilx-

2

创建一个包含只读属性和字段的类或结构体,如下所示:

 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;
      }
 }

2

是的,创建一个名为OutputFormat的类,其中包含Value、Filename和ID属性。你可以将数据存储在XML文件中,并解析XML文件到List中,或者你可以在代码的某个地方初始化OutputFormat对象。


1
// 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);

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接