如何对类属性进行字典定义

本文关键字:字典 定义 属性 | 更新日期: 2023-09-27 17:59:40

我有一个这样的类:

public class book
{
    public string Author {get; set;}
    public string Genre  {get; set;}
}

现在,例如,Genre应该是一个Dictionary,带有一个ID的不同流派的列表,所以当我创建一本新书时,我将Genre设置为Dictionary项目之一。

我该如何设置?我会有一个单独的Genre类来定义每个类吗?或者。。。我想我只是不确定如何处理它。

如何对类属性进行字典定义

是的,Genre类将是设置它的最佳方式。

 public class Book
    {
        public string Author {get; set;}
        public Genre Genre  {get; set;}
    }
    public class Genre
    {
        public string Id {get; set;}
        public string Name  {get; set;}
    }

但是,如果"dictionary"的字面意思是Dictionary,那么

public class Book
{
    public string Author {get; set;}
    public Dictionary<int, string> Genre  {get; set;}
}

也许是这样的?

public class Book
{
  public string Author { get; set; }
  public Genre Genre { get; set; }
  public Book(string author, Genre genre)
  {
    Author = author;
    Genre = genre;
  }
}
public class Genre 
{
  public string Name { get; set; }
  public static ICollection<Genre> List = new List<Genre>();
  public Genre(string name)
  {
    Name = name;
    List.Add(this);
  }
}