什么是“覆盖”的最佳方式枚举? [英] What is the best way to "override" enums?

查看:164
本文介绍了什么是“覆盖”的最佳方式枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

枚举继承

我有一些扩展抽象类的类。抽象父类定义具有一组值的枚举。一些子类继承父类的枚举值,但是一些子类需要枚举值不同。有什么办法可以以某种方式覆盖这些特定子类的枚举,如果没有,什么是实现我所描述的好方法?

I have a number of classes which extend an abstract class. The abstract parent class defines an enum with a set of values. Some of the subclasses inherit the parent class's enum values, but some of the subclasses need the enum values to be different. Is there any way to somehow override the enum for these particular subclasses, and if not, what is a good way to achieve what I'm describing?

class ParentClass
{
    private MyEnum m_EnumVal;
    public virtual MyEnum EnumVal
    {
        get { return m_EnumVal; }
        set { m_EnumVal = value; }
    }

    public enum MyEnum { a, b, c };
}

class ChildClass : ParentClass
{
    private MyEnum m_EnumVal;
    public virtual MyEnum EnumVal
    {
        get { return m_EnumVal; }
        set { m_EnumVal = value; }
    }

    public enum MyEnum { d, e, f };
}


推荐答案

其他答案是真的,如果您不拥有或不能修改原始基类或枚举。如果可以,那么您可以使用 typesafe枚举模式。它允许您定义自己的枚举类型,而不是从枚举派生,无论您想要他们做什么(包括支持继承)。

The other answers are true, if you don't own or can't modify the original base class or enumeration. If you can, then you could use the typesafe enum pattern. It allows you to define your own enum types, not derived from enum, that do whatever you want them to do (including support inheritance).

public class MyEnum
{
  public static readonly MyEnum A = new MyEnum("A");
  public static readonly MyEnum B = new MyEnum("B");
  public static readonly MyEnum C = new MyEnum("C");

  public override string ToString()
  {
    return Value;
  }

  protected MyEnum(string value)
  {
    this.Value = value;
  }

  public string Value { get; private set; }
}

public sealed class MyDerivedEnum : MyEnum
{
  public static readonly MyDerivedEnum D = new MyDerivedEnum("D");

  private MyDerivedEnum(string value)
    : base(value)
  {
  }
}

class Program
{
    static void Main(string[] args)
    {
        MyEnum blah = MyEnum.A;
        System.Console.WriteLine(blah);
        blah = MyDerivedEnum.D;
        System.Console.WriteLine(blah);
    }
}




A

D

按任意键继续。 。 。

A
D
Press any key to continue . . .

这篇关于什么是“覆盖”的最佳方式枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆