2009-06-09 60 views
1

我有以下语句:可空枚举(??)和LinqToSQL

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

ParentContentType是类型的ContentType

action.ParentContentType映射到这是一个可空INT数据库表的一个可为空的枚举。

如果action.ParentContentType 心不是空,我决定用枚举值:

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

在当action.ParentContentType IS空的情况下,我尝试将可空枚举的值设置为空。

这并不编译,我得到:

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'. 

回答

2

我会去你的ContentType.NullContentType.Empty否则你将所有的在整个应用程序进行检查空的想法...加ContentType.Empty是更具描述性的。

0

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

因为二者必须是同一类型的,并且null不能转换为值类型,它们都必须可空类型:

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

然而,这是非常模糊的。我从来没有想到,你可以创建一个枚举的空(我猜你可以,因为你发布了这个问题 - 我从来没有尝试过)。

您可能会更好,如您所说,枚举值意味着“无”。这对大多数开发人员来说不会那么令人惊讶。你只是不希望enum是空的。

+0

实际上,在这种情况下投射null会导致异常“无法翻译表达式”! – iasksillyquestions 2009-06-09 22:34:46

+0

这很奇怪。上面的代码为我编译和运行。你能发布ParentContentType类型的定义吗? – 2009-06-10 16:50:25

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'. 

跆拳道?