Nullable enums(??)和LinqToSQL

时间:2009-06-09 22:06:29

标签: linq-to-sql enums null

我有以下声明:

select new Action {
     ParentContentType = action.ParentContentType != null ? (ContentType)Enum.ToObject(typeof(ContentType), action.ParentContentType) : null 
};

ParentContentType是ContentType

类型的可为空的枚举

action.ParentContentType映射到可以为空的数据库表。

如果action.ParentContentType 不是 null,我使用以下方法确定枚举值:

(ContentType)Enum.ToObject(typeof(ContentType), action.ParentContentType)

如果action.ParentContentType IS 为null,我尝试将可为空的枚举设置为null。

这不编译,我得到:

Error   1 Type of conditional expression cannot be determined because there is no implicit conversion between ContentType' and '<null>' 

修改

可以创建一个空的枚举值..即ContentType.EMPTY。

然而:

ParentContentType = action.ParentContentType == null? ContentType.EMPTY:(ContentType)Enum.ToObject(typeof(ContentType),action.ParentContentType) };

也不起作用!

我得到例外:

The argument 'value' was the wrong type. Expected 'Enums.ContentType'. Actual 'System.Object'.

3 个答案:

答案 0 :(得分:2)

我会考虑您ContentType.NullContentType.Empty的想法,否则您将在整个应用程序中检查所有空值...加ContentType.Empty更具描述性。

答案 1 :(得分:1)

奇怪的是:

ParentContentType = action.ParentContentType == null ? ContentType.EMPTY : (ContentType)Enum.ToObject(typeof(ContentType), action.ParentContentType) 

导致异常:

The argument 'value' was the wrong type. Expected 'Enums.ContentType'. Actual 'System.Object'.

WTF?

答案 2 :(得分:0)

null是无类型的。你必须明确地转换它,因为? C#中的运算符要求第二个参数必须与第一个完全相同(或可隐式转换)。

因为两者必须属于同一类型,并且null不能转换为值类型,所以它们都必须是可空类型:

select new Action {
  ParentContentType = action.ParentContentType != null ?
    (ContentType?)Enum.ToObject(typeof(ContentType), action.ParentContentType) :
    (ContentType?)null 
};

然而,这非常模糊。我甚至从未想过你可以创建一个可枚举的枚举(我想你可以,因为你发布了这个问题 - 我从未尝试过)。

如你所说,你可能会更好地使用枚举值,这意味着“没有”。对于大多数开发人员来说,这不会令人惊讶。您只是不希望enum可以为空。

相关问题