【问题标题】:How to use enum in C# to create objects如何在 C# 中使用枚举来创建对象
【发布时间】:2015-03-26 12:43:36
【问题描述】:

我正在尝试使用枚举创建一个对象。我必须在 IceCream 类中制作冰淇淋,口味是巧克力和香草,草莓。由于我必须创建许多具有不同口味的产品(除其他外),因此我认为(正如我所见):

枚举口味{巧克力= 1,香草= 2,草莓= 3}; class IceCream{ public int type; //if it has two o more flavors public Flavors flavor; public IceCream(int type, Flavors flavor){ this.type = type; this.Flavors = flavor; } }

然后,我想在控制台中显示我的冰淇淋是什么口味的。如何创建对象并在控制台中显示风味?

谢谢

【问题讨论】:

  • 你能混合口味吗?喜欢巧克力和香草?
  • 可以,但我不知道该怎么做。

标签: c# class object enums


【解决方案1】:

您可以找到有用的 [Flags] 属性,因此您可以组合两个或多个值,如下所示:

class Program
{
    static void Main(string[] args)
    {
        var iceCream = new IceCream(Flavor.Chocolate | Flavor.Vanilla);
        Console.WriteLine("{0} has {1} flavors", 
            iceCream.Flavors, iceCream.FlavorCount);
    }
}

[Flags]
enum Flavor
{
    Chocolate   = 1 << 0,
    Vanilla     = 1 << 1, 
    Strawberry  = 1 << 2
};

class IceCream
{
    public Flavor Flavors { get; private set; }
    public int FlavorCount
    {
        get
        {
            return Enum.GetValues(typeof(Flavor)).Cast<Flavor>()
                       .Count(item => (item & this.Flavors) != 0);
        }
    }

    public IceCream() { }
    public IceCream(Flavor flavors)
    {
        this.Flavors = flavors;
    }
}

【讨论】:

    【解决方案2】:

    显而易见的有什么问题?

    var obj = new IceCream(1, Flavors.Vanilla);
    Console.WriteLine(obj.Flavors);
    

    【讨论】:

    • 对不起,我是初学者
    【解决方案3】:

    您可以像这样覆盖 base.ToString():

    public override string ToString()
    {
       return "Flavor is: " + flavor.ToString();
    }
    

    【讨论】:

    • 这似乎根本无法回答所提出的问题。
    • 编辑:这个想法是覆盖 ToString()。
    • 问题是如何从枚举中创建一个对象。这实际上与此无关
    • “那么,我想在控制台中显示我的冰淇淋是什么口味的”
    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    相关资源
    最近更新 更多