枚举+ IsDefined

时间:2013-10-30 16:34:35

标签: c# .net

鉴于此:

public enum SomeTypes
{
    SomeType1 = 1,
    SomeType2 = 2,
    SomeType3 = 3
}

和一个班级:

public SomeClass
{
public SomeTypes SomeType { get; set; };
}

检查枚举是否在范围内(即不是0)的最佳方法是什么。我猜它会涉及IsDefined?

2 个答案:

答案 0 :(得分:2)

public enum SomeTypes {
    SomeType1 = 1,
    SomeType2 = 2,
    SomeType3 = 3
}
public class SomeClass
{
    public SomeTypes SomeType { get; set; }

    bool validEnum() {
        return System.Enum.IsDefined(typeof(SomeTypes), this.SomeType);
    }
}

答案 1 :(得分:0)

您可以在set访问者中执行此操作:

public class SomeClass
{
    private SomeTypes _SomeType;
    public SomeTypes SomeType { 
        get {return _SomeType;} 
        set {
            if(!Enum.IsDefined(typeof(SomeTypes),value)) 
                throw new ArgumentException(string.Format("{0} is not a valid SomeTypes value", value),"value");
            _SomeType = value;
        }
    }
}