C# 将可为空的枚举从Sql读入SqlDataReader类

C# 将可为空的枚举从Sql读入SqlDataReader类,c#,enums,nullable,sqldatareader,C#,Enums,Nullable,Sqldatareader,假设我有如下定义的enum: public enum ServiceType : int { None= 0, TBB= 1, Doctor= 2, Organization = 3 } public Utility.ServiceType ? ServiceType { get; set; } 现在,在一个类中,我这样使用它: public enum ServiceType : int {

假设我有如下定义的enum:

  public enum ServiceType : int
    {
        None= 0,
        TBB= 1,
        Doctor= 2,
        Organization = 3
    }
 public Utility.ServiceType ? ServiceType  { get; set; }
现在,在一个类中,我这样使用它:

  public enum ServiceType : int
    {
        None= 0,
        TBB= 1,
        Doctor= 2,
        Organization = 3
    }
 public Utility.ServiceType ? ServiceType  { get; set; }
现在,我如何读取SqlDataReader类中存储在SQL中的值? 我试过了

ServiceType = reader["ServiceType "] as Utility.ServiceType ?

但是得到null作为一个值

我应该早点看。我道歉。我打赌这是一个拆箱问题。您可能必须这样做:

var field = reader["ServiceType"];
if (field == DBNull.Value)
    ServiceType = null;
else
    ServiceType = (Utility.ServiceType)(int)field;

reader[“ServiceType”]
应该是
reader[“ServiceType”]
?空间可能会引起问题。@MatthewHaugen。这是我复制代码时的错误。在我的原始代码中没有空格。我解决这个问题的方法是将对应的字段放在SQL必填字段中,默认值为“0”,因此我从SQL中读取值如下:
Enum.Parse(typeof(Utility.ServiceType),reader[“ServiceType”].ToString()作为Utility.ServiceType?
但我仍然对在名为ServiceType的字段中存在
NULL
值时如何从SQL中读取值感兴趣。