2

我们都知道,在 C# 中,ENUM 类型不能用数字(整数)定义

例如 public enum SOME_INTEGERS {3,6,8,11} 是不可能的

所以我的问题是,如何在 C# 中定义这种受限制的整数类型(一些选定整数的集合)?换句话说,我想定义一个像这样的变量:

private SOME_INTEGERS myVariable;

myVariable 可能只有值 3,6,8 或 11

4

3 回答 3

11

你可以使用这样的东西:

    public enum SOME_INTEGERS {
        One = 1,
        Three = 3,
        Five = 5
    }

    SOME_INTEGERS integer = SOME_INTEGERS.Three;
    Console.WriteLine((int)integer);//3
于 2013-09-16T14:49:56.183 回答
5

以下是一些选项:

// note that ((SomeIntegers)1) is a valid value with this scheme
public enum SomeIntegers { Three = 3, Six = 6, Eight = 8, Eleven = 11 }

// this stores the set of integers, but your logic to ensure the variable is
// one of these values must exist elsewhere, e.g. in property getters/setters
public ISet<int> SomeIntegers = new HashSet<int> {3,6,8,11};

// this class is a pseudo-enum, and with the exception of reflection,
// will ensure that only the specified values can be set
public sealed class SomeIntegers
{
    public static readonly SomeIntegers Three = new SomeIntegers(3);
    public static readonly SomeIntegers Six = new SomeIntegers(6);
    public static readonly SomeIntegers Eight = new SomeIntegers(8);
    public static readonly SomeIntegers Eleven = new SomeIntegers(11);
    public int Value { get; private set; }
    private SomeIntegers(int value)
    {
        this.Value = value;
    }
    public static implicit operator int(SomeIntegers someInteger)
    {
        return someInteger.Value;
    }
    public static explicit operator SomeIntegers(int value)
    {
        switch (value)
        {
            case 3:
                return Three;
            case 6:
                return Six;
            case 8:
                return Eight;
            case 11:
                return Eleven;
            default:
                throw new ArgumentException("Invalid value", "value");
        }
    }
    public override string ToString()
    {
        return this.Value.ToString();
    }
}
于 2013-09-16T14:52:07.557 回答
2

也许是一个结构:

struct MyInt
{
    static readonly int[] legalValues = { 3, 6, 8, 11 };

    public int Value
    {
        get;
        private set;
    }

    public bool IsIllegal
    {
        get
        {
            return Value == 0;
        }
    }

    MyInt(int value)
        : this()
    {
        Value = value;
    }

    public static implicit operator MyInt(int value)
    {
        if (legalValues.Contains(value))
        {
            return new MyInt(value);
        }

        return new MyInt();
    }
}

但是您可以创建非法值。

于 2013-09-16T15:00:41.757 回答