[英]How to do null check for enum
public class myclass
{
public Details DetailsInfo { get; set; }
public string name{ get; set; }
public string Email { get; set; }
public int subjects{ get; set; }
}
public enum subjects{
maths,
english,
science,
}
Among these subjects is an enum. 在这些主题中有一个枚举。 Even if I don't enter any value for subjects it takes 0 by default.
即使我没有为主题输入任何值,默认情况下它也是0。 This is the behavior of enum.
这是枚举的行为。 Is there any way to check if I have chose any value for subject.
有什么方法可以检查我是否为主题选择了任何值。
Note: I don't want to any value like undefined in the enum. 注意:我不想使用枚举中未定义的任何值。
You could solve the issue in two ways. 您可以通过两种方式解决该问题。
First, define a None
value (or whatever you want to name it) which represents 0
to indicate there is nothing chosen for an enum
value: 首先,定义一个
None
值(或您要命名的None
值),该值表示0
,表示没有选择enum
值:
public enum subjects{
None = 0, //define this
maths,
english,
science,
}
Alternatively, use Nullable<subjects>
or subjects?
或者,使用
Nullable<subjects>
还是subjects?
in your class ( myclass
). 在您的班级(
myclass
)中。
public class myclass
{
public Details DetailsInfo { get; set; }
public string name{ get; set; }
public string Email { get; set; }
public subjects? subj { get; set; } //note the question mark ?
}
Of the two methods, the first one is more common. 在这两种方法中,第一种较为常见。 Thus I would rather use the first one.
因此,我宁愿使用第一个。
You can change the class to look like this: 您可以将类更改为如下形式:
public class myclass
{
public Details DetailsInfo { get; set; }
public string name{ get; set; }
public string Email { get; set; }
public subjects? subject { get; set; }
}
So that the subject is nullable. 这样主题就可以为空。 It means that when you have not set it.
这意味着您尚未设置它。 It will be null
它将为空
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.