C#:如何使用枚举关键字

本文关键字:枚举 关键字 何使用 | 更新日期: 2023-09-27 18:36:47

我有以下代码,问题是当我尝试将国家/地区分配给客户时,出现错误。我需要知道如何分配声明为枚举的属性?我将在linq表达式中使用它,还有其他方法可以使用枚举吗?

var customers = new Customer[] {
    new Customer { Name= "Badhon",City=   "Dhaka",Country=Countries.Country.Bangladesh,Order= new Orders[] {
        new Orders { OrderID=1,ProductID=1,Quantity=2,Shipped=false,Month="Jan"}}},
    new Customer {Name = "Tasnuva",City = "Mirpur",Country =Countries .Country .Italy,Order =new Orders[] {
        new Orders { OrderID=2,ProductID=2,Quantity=5,Shipped=false,Month="Feb"}}}
}

我的enum定义如下:

public class  Countries
{
    public enum Country  {Italy,Japan,Bangladesh};
}

Customer如下:

public class Customer
{
    public string Name;
    public string City;
    public Countries Country;
    public Orders[] Order;
    public override string  ToString()
    {
        return string.Format("Name: {0} - City: {1} - Country: {2}", this.Name, this.City, this.Country);
    }
}

C#:如何使用枚举关键字

您的问题是您在客户中的字段属于 Countries 类型,而不是 Countries.Country 。而且您正在尝试分配一个显然不兼容的Countries.Country

枚举是一种类型,就像类一样。你不需要围绕它的类。你应该去掉那里的外部类:

public enum Country { Italy,Japan,Bangladesh }

并重新定义Customer中的字段:

public Country Country;

(是的,在 C# 中具有与类型同名的类成员)。

另一个问题:您可能应该使用属性而不是字段:

public Country Country { get; set; }

这将使您的生活更轻松(您可以像现在一样使用它,直到您阅读了差异)。