0

I have a base class for enumerations that looks similar to the example below. My actual implementation covers far more such as explicit and implicit castings, reflection, flags and exception handling, but basically, it's just this:

public abstract class Enumeration<T> {

    // enum value
    protected readonly T _value;

    // collection of all values
    private static readonly HashSet<Enumeration<T>> _values
       = new HashSet<Enumeration<T>>();

    public T Value {
        get { return _value; }
    }

    // returns all values
    public static IEnumerable<Enumeration<T>> GetValues() {
        return _values.AsEnumerable();
    }
}

Now, whenever I would like to have an enumeration of a certain type (may it be string, integer etc. I'm not so caged like with the usual C# enum), I can declare it this way:

public sealed class MyEnum : Enumeration<string> {

    public static readonly MyEnum EnumVal1 = new MyEnum("Val1!");
    public static readonly MyEnum EnumVal2 = new MyEnum("Val2!");
    public static readonly MyEnum EnumVal3 = new MyEnum("Val3!");

}

And make it either expandable or not by using a private or public constructor:

public MyEnum(string enumVal) : base(value: enumVal) {}

which passes the values to the base ctor:

protected Enumeration(T value) {
    _value = value;
    _values.Add(this);
}

This works fine for types like string, int, double etc. But what if I would like to enumerate complex objects?

public sealed class ComplexObj: Enumeration<ComplexObj> {

    public static readonly ComplexObj Val1 = new ComplexObj("val1", 455, null);

}

Here do the problems start, as I'm not able to pass the instanced objects to the base constructor:

public ComplexObj(string name, int someval, string another)
    : base(this) {} // doesn't work

And passing a new object to the constructor would lead to.. you know :)

: base(new ComplexObj(name, someval, another)) {} // lol

How could I solve this problem? Is there a way to pass the object itself to the base constructor?

4

1 回答 1

3

这是一种我不会使用的枚举,但如果您想这样做,那么这将是解决方案:

public sealed class MyComplexObjEnum : Enumeration<ComplexObj>
{
    public MyComplexObjEnum(ComplexObj enumVal) : base( enumVal) { }
    public static readonly MyComplexObjEnum EnumVal1 = new MyComplexObjEnum(new ComplexObj("val1", 455, null));
    public static readonly MyComplexObjEnum EnumVal2 = new MyComplexObjEnum(new ComplexObj("val2", 456, null));
    public static readonly MyComplexObjEnum EnumVal3 = new MyComplexObjEnum(new ComplexObj("val3", 457, null));
}

public class ComplexObj 
{
    private readonly string _a;
    private readonly int _b;
    private readonly string _c;

    public ComplexObj(string a, int b, string c)
    {
        _a = a;
        _b = b;
        _c = c;
    }
}
于 2013-07-30T10:19:35.307 回答