Я хочу построить шаблон перечисления в стиле Java для C #, который также поддерживает наследование.У меня проблемы с доходностью.В частности, возвращая значения BaseEnum из свойства значений ChildEnum.
public class BaseEnum {
public static readonly BaseEnum A = new BaseEnum("A");
public static readonly BaseEnum B = new BaseEnum("B");
public static readonly BaseEnum C = new BaseEnum("C");
public static IEnumerable<BaseEnum> Values {
get {
yield return A;
yield return B;
yield return C;
}
}
public readonly String Name;
protected BaseEnum(String name) {
this.Name = name;
}
public static void TestMain() {
Console.WriteLine("BaseEnum, should print (A,B,C):");
foreach(BaseEnum e in BaseEnum.Values) {
Console.WriteLine(e.Name);
}
Console.WriteLine("BaseEnum in ChildEnum, should print (A,B,C,D,E):");
foreach(BaseEnum e in ChildEnum.Values) {
Console.WriteLine(e.Name);
}
Console.WriteLine("ChildEnum in ChildEnum, should print (D,E):");
foreach(ChildEnum e in ChildEnum.Values) {
Console.WriteLine(e.Name);
}
}
}
class ChildEnum : BaseEnum {
public static readonly ChildEnum D = new ChildEnum("D");
public static readonly ChildEnum E = new ChildEnum("E");
new public static IEnumerable<BaseEnum> Values {
get {
// yield return BaseEnum.Values; // This is what I want to do. It gives the error message below:
// Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Abra.Workshop.EnumABC>'
// to 'Abra.Workshop.EnumABC'. An explicit conversion exists (are you missing a cast?)
yield return D;
yield return E;
}
}
public ChildEnum(string name)
: base(name) {
}
}
/* Output!
BaseEnum, should print (A,B,C):
A
B
C
BaseEnum in ChildEnum, should print (A,B,C,D,E):
D
E
ChildEnum in ChildEnum, should print (D,E):
D
E
*/