2009-06-09 82 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'. 

跆拳道?