【问题标题】:Nullable enums(??) and LinqToSQL可空枚举(??)和 LinqToSQL
【发布时间】:2009-06-10 06:43:29
【问题描述】:

我有如下声明:

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

ParentContentType 是 ContentType 类型的可为空枚举

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

如果 action.ParentContentType isnt 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'.

【问题讨论】:

    标签: linq-to-sql enums null


    【解决方案1】:

    我会同意您的 ContentType.NullContentType.Empty 的想法,否则您将在整个应用程序中检查空值...另外,ContentType.Empty 更具描述性。

    【讨论】:

      【解决方案2】:

      奇怪:

      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?

      【讨论】:

      • ParentContentType 也是枚举吗?那么它应该有一个 ContentType.Empty 吗?
      • action.ParentContentType 是一个可为空的 int 并且来自数据库
      • 但是,数据库中的值永远不应该 == null。哦!
      • 上面也为我编译和运行。我不知道——我们肯定遗漏了关于类型定义的一些内容。
      • 我刚刚在我维护的代码库中遇到了这个问题。不知道解决方案是什么?
      【解决方案3】:

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

      因为两者必须是相同的类型,并且null不能被强制转换为值类型,所以它们都必须是可为空的类型:

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

      但是,这很模糊。我从来没有想过你可以创建一个可以为空的枚举(我想你可以,因为你发布了这个问题——我从来没有尝试过)。

      正如您所建议的,使用表示“无”的枚举值可能会更好。对于大多数开发人员来说,这并不令人惊讶。您只是不希望 enum 可以为空。

      【讨论】:

      • 实际上在这种情况下强制转换 null 会导致异常“无法翻译表达式”!
      • 这很奇怪。上面的代码为我编译并运行。能贴一下ParentContentType的类型定义吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多