整数集作为自己的数据类型

时间:2013-09-16 14:45:10

标签: c# .net

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

e.g。 public enum SOME_INTEGERS {3,6,8,11}是不可能的

所以我的问题是,我怎样才能在C#中定义这样一个resticted类型的整数(一些选定整数的集合)? 换句话说,我想定义一个这样的变量:

private SOME_INTEGERS myVariable;

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

3 个答案:

答案 0 :(得分:11)

您可以使用以下内容:

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

    SOME_INTEGERS integer = SOME_INTEGERS.Three;
    Console.WriteLine((int)integer);//3

答案 1 :(得分: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();
    }
}

答案 2 :(得分: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();
    }
}

但您可以创建非法值。