是否可以创建包含数组的枚举?

duk*_*kem 5 c# enums

我想声明几个常量对象,每个对象都有两个子对象,我想将它们存储起来enum用于组织目的.

是否有可能在C#中做这样的事情?

enum Car
{
  carA = { 'ford', 'red' }
  carB = { 'bmw', 'black' }
  carC = { 'toyota', 'white' }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_* J. 4

不可以,C# 语言不允许这样做。

您可以创建一个

Dictionary<Car, List<string>> cars;
Run Code Online (Sandbox Code Playgroud)

您可以向其中添加条目,例如

cars = new Dictionary<Car, List<String>>();
cars.Add(Car.carA, new List<String>() { "ford", "red" });
Run Code Online (Sandbox Code Playgroud)

但请注意,如果您混合“福特”和“红色”的概念,您可能需要考虑创建一个对象来表示该事物,例如

public class CarDetails
{
    public string Maker { get; set; }
    public string Color { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后,你的Dictionary对象看起来像

Dictionary<Car, CarDetails> cars;
cars = new Dictionary<Car.carA, CarDetails>();

cars.Add(Car.carA, new CarDetails() { Maker = "ford", Color = "red" });
Run Code Online (Sandbox Code Playgroud)