.net Nullable Enum 可空类型问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/426497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:56:24  来源:igfitidea点击:

Nullable Enum nullable type question

.netc#-2.0nullable

提问by Michael Kniskern

I get the following compilation error with the following source code:

我使用以下源代码收到以下编译错误:

Compilation Error:

编译错误:

Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'MyEnum'

无法确定条件表达式的类型,因为 '' 和 'MyEnum' 之间没有隐式转换

Source Code

源代码

public enum MyEnum
{
    Value1, Value2, Value3
}

public class MyClass
{
    public MyClass() {}
    public MyEnum? MyClassEnum { get; set; }
}

public class Main()
{
   object x = new object();

   MyClass mc = new MyClass()
   {
        MyClassEnum = Convert.IsDBNull(x) : null ? 
            (MyEnum) Enum.Parse(typeof(MyEnum), x.ToString(), true)
   };
}

How can I resolve this error?

我该如何解决这个错误?

回答by Luke Quinane

I think you just need to cast the result of Enum.Parseto MyEnum?. This is the case with nullable ints at least. E.g.:

我认为您只需要将结果转换为Enum.Parseto MyEnum?。至少可空整数就是这种情况。例如:

int? i;
i = shouldBeNull ? null : (int?) 123;

So:

所以:

MyClassEnum = Convert.IsDBNull(x)
    ? null
    : (MyEnum?) Enum.Parse(typeof(MyEnum), x.ToString(), true)

回答by M4N

There is a syntax error in your code: the position of ':' and '?' must be exchanged:

您的代码中存在语法错误:':' 和 '?' 的位置 必须交换:

MyClassEnum = Convert.IsDBNull(x) ? null : 
            (MyEnum) Enum.Parse(typeof(MyEnum), x.ToString(), true)

BTW:

顺便提一句:

as far as I know, the recommended way is to use a enum-element named 'None' instead of a Nullable enum, e.g:

据我所知,推荐的方法是使用名为“None”的枚举元素而不是 Nullable 枚举,例如:

public enum MyEnum
{
    None, Value1, Value2, Value3
}

and

MyClassEnum = Convert.IsDBNull(x) ? MyEnum.None : 
            (MyEnum) Enum.Parse(typeof(MyEnum), x.ToString(), true);

回答by Michael Kniskern

I think you will just need to cast the result to (MyEnum?) rather than (MyEnum)?

我认为您只需要将结果转换为 (MyEnum?) 而不是 (MyEnum)?