枚举“继承”

时间:2009-04-16 19:27:08

标签: c# .net enums

我在低级命名空间中有一个枚举。我想在一个“继承”低级别枚举的中级命名空间中提供一个类或枚举。

namespace low
{
   public enum base
   {
      x, y, z
   }
}

namespace mid
{
   public enum consume : low.base
   {
   }
}

我希望这是可能的,或者某种可以取代枚举消耗的类,它将为枚举提供一层抽象,但仍然让该类的实例访问枚举。

思想?

编辑: 我之所以没有将其转换为类中的一个原因,其中一个原因是我必须使用的服务需要低级别的枚举。我得到了WSDL和XSD,它们将结构定义为枚举。该服务无法更改。

15 个答案:

答案 0 :(得分:433)

这是不可能的。枚举不能从其他枚举继承。事实上,所有枚举都必须实际上从System.Enum继承。 C#允许语法更改看起来像继承的枚举值的基础表示,但实际上它们仍然继承自System.enum。

有关详细信息,请参阅CLI spec的第8.5.2节。来自规范的相关信息

  • 所有枚举必须来自System.Enum
  • 由于上述原因,所有枚举都是值类型,因此密封

答案 1 :(得分:153)

您可以通过课程实现您想要的目标:

public class Base
{
    public const int A = 1;
    public const int B = 2;
    public const int C = 3;
}
public class Consume : Base
{
    public const int D = 4;
    public const int E = 5;
}

现在,您可以使用与枚举时类似的类:

int i = Consume.B;

更新(更新问题后):

如果将相同的int值分配给现有枚举中定义的常量,则可以在枚举和常量之间进行转换,例如:

public enum SomeEnum // this is the existing enum (from WSDL)
{
    A = 1,
    B = 2,
    ...
}
public class Base
{
    public const int A = (int)SomeEnum.A;
    //...
}
public class Consume : Base
{
    public const int D = 4;
    public const int E = 5;
}

// where you have to use the enum, use a cast:
SomeEnum e = (SomeEnum)Consume.B;

答案 2 :(得分:107)

简短的回答是否定的。如果你愿意,你可以玩一点:

您可以随时执行以下操作:

private enum Base
{
    A,
    B,
    C
}

private enum Consume
{
    A = Base.A,
    B = Base.B,
    C = Base.C,
    D,
    E
}

但是,它并没有那么好用,因为Base.A!= Consume.A

你可以随时做这样的事情:

public static class Extensions
{
    public static T As<T>(this Consume c) where T : struct
    {
        return (T)System.Enum.Parse(typeof(T), c.ToString(), false);
    }
}

为了跨越Base和Consume ...

您还可以将枚举的值转换为整数,并将它们作为整数而不是整数进行比较,但这种情况也很糟糕。

扩展方法return应该输入类型T。

答案 3 :(得分:91)

上面使用具有int常量的类的解决方案缺乏类型安全性。即您可以创建实际上未在类中定义的新值。 此外,例如,编写一个将这些类之一作为输入的方法是不可能的。

你需要写

public void DoSomethingMeaningFull(int consumeValue) ...

但是,当没有可用的枚举时,有一个基于类的Java解决方案。这提供了几乎类似于枚举的行为。唯一需要注意的是,这些常量不能在switch语句中使用。

public class MyBaseEnum
{
    public static readonly MyBaseEnum A = new MyBaseEnum( 1 );
    public static readonly MyBaseEnum B = new MyBaseEnum( 2 );
    public static readonly MyBaseEnum C = new MyBaseEnum( 3 );

    public int InternalValue { get; protected set; }

    protected MyBaseEnum( int internalValue )
    {
        this.InternalValue = internalValue;
    }
}

public class MyEnum : MyBaseEnum
{
    public static readonly MyEnum D = new MyEnum( 4 );
    public static readonly MyEnum E = new MyEnum( 5 );

    protected MyEnum( int internalValue ) : base( internalValue )
    {
        // Nothing
    }
}

[TestMethod]
public void EnumTest()
{
    this.DoSomethingMeaningful( MyEnum.A );
}

private void DoSomethingMeaningful( MyBaseEnum enumValue )
{
    // ...
    if( enumValue == MyEnum.A ) { /* ... */ }
    else if (enumValue == MyEnum.B) { /* ... */ }
    // ...
}

答案 4 :(得分:13)

忽略base是保留字的事实,你不能继承enum。

你能做的最好的事情就是这样:

public enum Baseenum
{
   x, y, z
}

public enum Consume
{
   x = Baseenum.x,
   y = Baseenum.y,
   z = Baseenum.z
}

public void Test()
{
   Baseenum a = Baseenum.x;
   Consume newA = (Consume) a;

   if ((Int32) a == (Int32) newA)
   {
   MessageBox.Show(newA.ToString());
   }
}

由于它们都是相同的基类型(即:int),因此您可以将一个类型的实例的值分配给另一个类型的实例。不理想,但它有效。

答案 5 :(得分:6)

我知道这个答案有点迟,但这就是我最终做的事情:

public class BaseAnimal : IEquatable<BaseAnimal>
{
    public string Name { private set; get; }
    public int Value { private set; get; }

    public BaseAnimal(int value, String name)
    {
        this.Name = name;
        this.Value = value;
    }

    public override String ToString()
    {
        return Name;
    }

    public bool Equals(BaseAnimal other)
    {
        return other.Name == this.Name && other.Value == this.Value;
    }
}

public class AnimalType : BaseAnimal
{
    public static readonly BaseAnimal Invertebrate = new BaseAnimal(1, "Invertebrate");

    public static readonly BaseAnimal Amphibians = new BaseAnimal(2, "Amphibians");

    // etc        
}

public class DogType : AnimalType
{
    public static readonly BaseAnimal Golden_Retriever = new BaseAnimal(3, "Golden_Retriever");

    public static readonly BaseAnimal Great_Dane = new BaseAnimal(4, "Great_Dane");

    // etc        
}

然后我可以做以下事情:

public void SomeMethod()
{
    var a = AnimalType.Amphibians;
    var b = AnimalType.Amphibians;

    if (a == b)
    {
        // should be equal
    }

    // call method as
    Foo(a);

    // using ifs
    if (a == AnimalType.Amphibians)
    {
    }
    else if (a == AnimalType.Invertebrate)
    {
    }
    else if (a == DogType.Golden_Retriever)
    {
    }
    // etc          
}

public void Foo(BaseAnimal typeOfAnimal)
{
}

答案 6 :(得分:4)

这就是我所做的。我所做的不同的是在“消费”new上使用相同的名称和enum关键字。由于enum的名称是相同的,您可以盲目地使用它,它是正确的。另外,你得到intellisense。您只需在设置时手动注意将值从基座复制并保持同步。您可以提供代码注释。这是为什么在数据库中存储enum值时我始终存储字符串而不是值的另一个原因。因为如果您使用自动分配的递增整数值,那么这些值可能随时间而变化。

// Base Class for balls 
public class BaseBall
{
    // keep synced with subclasses!
    public enum Sizes
    {
        Small,
        Medium,
        Large
    }
}

public class VolleyBall : BaseBall
{
    // keep synced with base class!
    public new enum Sizes
    {
        Small = BaseBall.Sizes.Small,
        Medium = BaseBall.Sizes.Medium,
        Large = BaseBall.Sizes.Large,
        SmallMedium,
        MediumLarge,
        Ginormous
    }
}

答案 7 :(得分:1)

枚举不是实际的类,即使它们看起来像它。在内部,它们被视为基础类型(默认情况下为Int32)。因此,您只能通过将单个值从一个枚举“复制”到另一个枚举并将它们转换为整数来比较它们的相等性来实现此目的。

答案 8 :(得分:1)

枚举不能从其他枚举中获取,只能来自int,uint,short,ushort,long,ulong,byte和sbyte。

像Pascal说的那样,你可以使用其他枚举的值或常量来初始化枚举值,但这就是它。

答案 9 :(得分:1)

另一种可能的解决方案:

public enum @base
{
    x,
    y,
    z
}

public enum consume
{
    x = @base.x,
    y = @base.y,
    z = @base.z,

    a,b,c
}

// TODO: Add a unit-test to check that if @base and consume are aligned

HTH

答案 10 :(得分:1)

这是不可能的(正如@JaredPar已经提到的那样)。试图通过逻辑来解决这个问题是一种不好的做法。如果您的base class具有enum,则应该列出所有可能的enum-values,并且类的实现应该与它知道的值一起使用。

E.g。假设您有一个基类BaseCatalog,它有一个enum ProductFormatsDigitalPhysical)。然后,您可以拥有可能同时包含MusicCatalogBookCatalog个产品的DigitalPhysical,但如果该类为ClothingCatalog,则其应仅包含Physical 1}}产品。

答案 11 :(得分:1)

替代解决方案

在我的公司中,我们避免“跳过项目”进入非常见的较低级别的项目。例如,我们的表示/ API层只能引用我们的域层,而域层只能引用数据层。

但是,当存在表示层和域层都需要引用的枚举时,这是一个问题。

这是我们到目前为止已实现的解决方案。这是一个很好的解决方案,对我们来说效果很好。其他答案都围绕着这个问题。

基本前提是枚举不能被继承-但类可以被继承。所以...

// In the lower level project (or DLL)...
public abstract class BaseEnums
{
    public enum ImportanceType
    {
        None = 0,
        Success = 1,
        Warning = 2,
        Information = 3,
        Exclamation = 4
    }

    [Flags]
    public enum StatusType : Int32
    {
        None = 0,
        Pending = 1,
        Approved = 2,
        Canceled = 4,
        Accepted = (8 | Approved),
        Rejected = 16,
        Shipped = (32 | Accepted),
        Reconciled = (64 | Shipped)
    }

    public enum Conveyance
    {
        None = 0,
        Feet = 1,
        Automobile = 2,
        Bicycle = 3,
        Motorcycle = 4,
        TukTuk = 5,
        Horse = 6,
        Yak = 7,
        Segue = 8
    }

然后,“继承”另一个更高级别项目中的枚举...

// Class in another project
public sealed class SubEnums: BaseEnums
{
   private SubEnums()
   {}
}

这具有三个真正的优势...

  1. 两个项目中的枚举定义自动相同- 定义。
  2. 对枚举定义的任何更改都是自动的 在第二个中回显,而不必对 二等。
  3. 枚举基于相同的代码-因此可以轻松地比较值(有一些警告)。

要引用第一个项目中的枚举,可以使用类的前缀: BaseEnums.StatusType.Pending 或使用静态BaseEnums添加“ ;“ 声明使用。

第二个项目中,当处理继承的类时,我无法使用“使用静态...” 方法,因此所有对“继承的枚举”将以该类作为前缀,例如 SubEnums.StatusType.Pending 。如果有人提出允许在第二个项目中使用“使用静态” 方法的方法,请告诉我。

我确信可以对其进行调整以使其变得更好-但这确实有效,并且我在工作项目中使用了这种方法。

如果对您有帮助,请对其进行投票。

答案 12 :(得分:0)

我还希望重载枚举,并创建了the answer of 'Seven' on this pagethe answer of 'Merlyn Morgan-Graham' on a duplicate post of this的混合,以及一些改进。
我的解决方案优于其他解决方案的主要优势:

  • 基础int值的自动递增
  • 自动命名

这是一个开箱即用的解决方案,可以直接插入您的项目中。它是根据我的需求而设计的,所以如果您不喜欢它的某些部分,只需用您自己的代码替换它们。

首先,所有自定义枚举都应该继承基类CEnum。它具有基本功能,类似于.net Enum类型:

public class CEnum
{
  protected static readonly int msc_iUpdateNames  = int.MinValue;
  protected static int          ms_iAutoValue     = -1;
  protected static List<int>    ms_listiValue     = new List<int>();

  public int Value
  {
    get;
    protected set;
  }

  public string Name
  {
    get;
    protected set;
  }

  protected CEnum ()
  {
    CommonConstructor (-1);
  }

  protected CEnum (int i_iValue)
  {
    CommonConstructor (i_iValue);
  }

  public static string[] GetNames (IList<CEnum> i_listoValue)
  {
    if (i_listoValue == null)
      return null;
    string[] asName = new string[i_listoValue.Count];
    for (int ixCnt = 0; ixCnt < asName.Length; ixCnt++)
      asName[ixCnt] = i_listoValue[ixCnt]?.Name;
    return asName;
  }

  public static CEnum[] GetValues ()
  {
    return new CEnum[0];
  }

  protected virtual void CommonConstructor (int i_iValue)
  {
    if (i_iValue == msc_iUpdateNames)
    {
      UpdateNames (this.GetType ());
      return;
    }
    else if (i_iValue > ms_iAutoValue)
      ms_iAutoValue = i_iValue;
    else
      i_iValue = ++ms_iAutoValue;

    if (ms_listiValue.Contains (i_iValue))
      throw new ArgumentException ("duplicate value " + i_iValue.ToString ());
    Value = i_iValue;
    ms_listiValue.Add (i_iValue);
  }

  private static void UpdateNames (Type i_oType)
  {
    if (i_oType == null)
      return;
    FieldInfo[] aoFieldInfo = i_oType.GetFields (BindingFlags.Public | BindingFlags.Static);

    foreach (FieldInfo oFieldInfo in aoFieldInfo)
    {
      CEnum oEnumResult = oFieldInfo.GetValue (null) as CEnum;
      if (oEnumResult == null)
        continue;
      oEnumResult.Name = oFieldInfo.Name;
    }
  }
}

其次,这里有2个派生的枚举类。所有派生类都需要一些基本方法才能按预期工作。它始终是相同的样板代码;我还没有找到将其外包给基类的方法。第一级继承的代码与所有后续级别略有不同。

public class CEnumResult : CEnum
{
  private   static List<CEnumResult>  ms_listoValue = new List<CEnumResult>();

  public    static readonly CEnumResult Nothing         = new CEnumResult (  0);
  public    static readonly CEnumResult SUCCESS         = new CEnumResult (  1);
  public    static readonly CEnumResult UserAbort       = new CEnumResult ( 11);
  public    static readonly CEnumResult InProgress      = new CEnumResult (101);
  public    static readonly CEnumResult Pausing         = new CEnumResult (201);
  private   static readonly CEnumResult Dummy           = new CEnumResult (msc_iUpdateNames);

  protected CEnumResult () : base ()
  {
  }

  protected CEnumResult (int i_iValue) : base (i_iValue)
  {
  }

  protected override void CommonConstructor (int i_iValue)
  {
    base.CommonConstructor (i_iValue);

    if (i_iValue == msc_iUpdateNames)
      return;
    if (this.GetType () == System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType)
      ms_listoValue.Add (this);
  }

  public static new CEnumResult[] GetValues ()
  {
    List<CEnumResult> listoValue = new List<CEnumResult> ();
    listoValue.AddRange (ms_listoValue);
    return listoValue.ToArray ();
  }
}

public class CEnumResultClassCommon : CEnumResult
{
  private   static List<CEnumResultClassCommon> ms_listoValue = new List<CEnumResultClassCommon>();

  public    static readonly CEnumResult Error_InternalProgramming           = new CEnumResultClassCommon (1000);

  public    static readonly CEnumResult Error_Initialization                = new CEnumResultClassCommon ();
  public    static readonly CEnumResult Error_ObjectNotInitialized          = new CEnumResultClassCommon ();
  public    static readonly CEnumResult Error_DLLMissing                    = new CEnumResultClassCommon ();
  // ... many more
  private   static readonly CEnumResult Dummy                               = new CEnumResultClassCommon (msc_iUpdateNames);

  protected CEnumResultClassCommon () : base ()
  {
  }

  protected CEnumResultClassCommon (int i_iValue) : base (i_iValue)
  {
  }

  protected override void CommonConstructor (int i_iValue)
  {
    base.CommonConstructor (i_iValue);

    if (i_iValue == msc_iUpdateNames)
      return;
    if (this.GetType () == System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType)
      ms_listoValue.Add (this);
  }

  public static new CEnumResult[] GetValues ()
  {
    List<CEnumResult> listoValue = new List<CEnumResult> (CEnumResult.GetValues ());
    listoValue.AddRange (ms_listoValue);
    return listoValue.ToArray ();
  }
}

已经使用以下代码成功测试了类:

private static void Main (string[] args)
{
  CEnumResult oEnumResult = CEnumResultClassCommon.Error_Initialization;
  string sName = oEnumResult.Name;   // sName = "Error_Initialization"

  CEnum[] aoEnumResult = CEnumResultClassCommon.GetValues ();   // aoEnumResult = {testCEnumResult.Program.CEnumResult[9]}
  string[] asEnumNames = CEnum.GetNames (aoEnumResult);
  int ixValue = Array.IndexOf (aoEnumResult, oEnumResult);    // ixValue = 6
}

答案 13 :(得分:0)

我知道我参加这个聚会有点晚了,但这是我的两分钱。

我们都很清楚该框架不支持Enum继承。在该线程中提出了一些非常有趣的解决方法,但是没有一种感觉完全符合我的期望,因此我自己进行了研究。

简介:ObjectEnum

您可以在这里查看代码和文档:https://github.com/dimi3tron/ObjectEnum

包在这里:https://www.nuget.org/packages/ObjectEnum

或者直接安装:Install-Package ObjectEnum

简而言之,ObjectEnum<TEnum>充当任何枚举的包装。通过覆盖子类中的GetDefinedValues(),可以指定哪些枚举值对该特定类有效。

已添加许多运算符重载,以使ObjectEnum<TEnum>实例的行为就像是基础枚举的实例一样,同时要记住定义的值限制。这意味着您可以轻松地将实例与int或enum值进行比较,从而在切换条件或任何其他条件下使用它。

我想参考上面的github回购中的示例和更多信息。

希望您觉得这有用。随意发表评论或在github上发表问题以获取进一步的想法或评论。

以下是您可以使用ObjectEnum<TEnum>进行操作的一些简短示例:

var sunday = new WorkDay(DayOfWeek.Sunday); //throws exception
var monday = new WorkDay(DayOfWeek.Monday); //works fine
var label = $"{monday} is day {(int)monday}." //produces: "Monday is day 1."
var mondayIsAlwaysMonday = monday == DayOfWeek.Monday; //true, sorry...

var friday = new WorkDay(DayOfWeek.Friday);

switch((DayOfWeek)friday){
    case DayOfWeek.Monday:
        //do something monday related
        break;
        /*...*/
    case DayOfWeek.Friday:
        //do something friday related
        break;
}

答案 14 :(得分:-6)

您可以在枚举中执行继承,但它仅限于以下类型。 int,uint,byte,sbyte,short,ushort,long,ulong

E.g。

public enum Car:int{
Toyota,
Benz,
}
相关问题