如何在C#中使用枚举来创建对象

时间:2015-03-26 12:43:37

标签: c# class object enums

我试图用枚举创建一个对象。我必须在IceCream课程中制作冰淇淋,其中的味道是巧克力和香草,草莓。因为我必须创造许多不同口味的东西(除其他外),我想在这些(我已经看到):

enum Flavors { Chocolate = 1, Vanilla = 2, Strawberry = 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; } }

然后,我想在控制台中展示我的冰淇淋有什么味道。我如何创建一个对象并在控制台中显示什么味道?

由于

3 个答案:

答案 0 :(得分:3)

您可以找到有用的[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;
    }
}

答案 1 :(得分:0)

显而易见的是什么问题?

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

答案 2 :(得分:-1)

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

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