鉴于此:
public enum SomeTypes
{
SomeType1 = 1,
SomeType2 = 2,
SomeType3 = 3
}
和一个班级:
public SomeClass
{
public SomeTypes SomeType { get; set; };
}
检查枚举是否在范围内(即不是0)的最佳方法是什么。我猜它会涉及IsDefined?
答案 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;
}
}
}