封装枚举

本文关键字:枚举 封装 | 更新日期: 2023-09-27 18:03:15

我正在尝试理解如何在c#中使用枚举。我已经在谷歌上搜索过了,但我不知道如何封装枚举。

我有一个包含枚举属性的类。如何封装此属性以便在类之外使用它?

private enum cost { Price, Diff };

封装枚举

你必须声明枚举:

  public enum Cost { 
    Price, 
    Diff 
  };

然后使用

  public class MyClass {
    // property of "Cost" type
    public Cost MyCost {
      get;
      set; 
    }
    ...
  }

您可以将枚举声明移出类,如下所示,然后它可以在整个项目中用作cost cos = cost.Price

public enum cost 
    {
        Price, Diff
    }
    public class ExampleClass
    {
    }

只需将enum视为普通的类对象。

假设你有这个enum:

public enum CoffeType
{
    regular,
    decaf
}

你有一个类:

public class CoffeeOrder
{
    public string CustomerName {get;set}
    public CoffeeType CoffeeType {get;set;}
    // ..other properties 
}

,你会看到enum就像普通的类属性一样被封装了…