在 C# 中使用条件运算符键入结果 [英] Type result with conditional operator in C#

查看:35
本文介绍了在 C# 中使用条件运算符键入结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用条件运算符,但我对它认为结果应该是的类型感到困惑.

I am trying to use the conditional operator, but I am getting hung up on the type it thinks the result should be.

以下是我试图展示我遇到的问题的示例:

Below is an example that I have contrived to show the issue I am having:

class Program
{
    public static void OutputDateTime(DateTime? datetime)
    {
        Console.WriteLine(datetime);
    }

    public static bool IsDateTimeHappy(DateTime datetime)
    {
        if (DateTime.Compare(datetime, DateTime.Parse("1/1")) == 0)
            return true;

        return false;
    }

    static void Main(string[] args)
    {
        DateTime myDateTime = DateTime.Now;
        OutputDateTime(IsDateTimeHappy(myDateTime) ? null : myDateTime);
        Console.ReadLine();                        ^
    }                                              |
}                                                  |
// This line has the compile issue  ---------------+

在上面指出的那一行,我得到以下编译错误:

On the line indicated above, I get the following compile error:

无法确定条件表达式的类型,因为'<之间没有隐式转换.null >' 和 'System.DateTime'

我很困惑,因为参数是可以为空的类型(DateTime?).为什么它需要转换?如果为空,则使用它,如果是日期时间,则使用它.

I am confused because the parameter is a nullable type (DateTime?). Why does it need to convert at all? If it is null then use that, if it is a date time then use that.

我的印象是:

condition ? first_expression : second_expression;

与以下内容相同:

if (condition)
   first_expression;
else
   second_expression;

显然情况并非如此.这背后的原因是什么?

Clearly this is not the case. What is the reasoning behind this?

(注意:我知道如果我将myDateTime"设为可为空的 DateTime,那么它将起作用.但为什么需要它?

(NOTE: I know that if I make "myDateTime" a nullable DateTime then it will work. But why does it need it?

正如我之前所说,这是一个人为的例子.在我的真实示例中,myDateTime"是一个不能为空的数据映射值.)

As I stated earlier this is a contrived example. In my real example "myDateTime" is a data mapped value that cannot be made nullable.)

推荐答案

编译器不是根据结果的使用来推断条件运算符结果的类型,而是根据其参数的类型.编译器在看到这个表达式时会失败,因为它无法推断出结果的类型:

The compiler does not infer the type of the result of the conditional operator from the usage of the result, but from the types of its arguments. The compiler fails when it sees this expression because it cannot deduce the type of the result:

IsDateTimeHappy(myDateTime) ? null : myDateTime;

由于 nullDateTime 不兼容,你需要告诉编译器应该是什么类型.演员应该可以解决问题:

Since null and DateTime are not compatible, you need to tell the compiler what the type should be. A cast should do the trick:

DateTime? x = IsDateTimeHappy(myDateTime) ? (DateTime?)null : myDateTime;
OutputDateTime(x);

现在编译器将没有问题.如果您愿意,也可以将上述内容写在一行上(但我可能不会这样做):

Now the compiler will have no problems. You can also write the above on one line if you prefer (but I would probably not do this):

OutputDateTime(IsDateTimeHappy(myDateTime) ? (DateTime?)null : myDateTime);

Eric Lippert 有一个 good answer 这也与此处相关,并详细介绍了编译器如何确定类型.

Eric Lippert has a good answer that is also relevant here and goes into more details about how the compiler determines types.

这篇关于在 C# 中使用条件运算符键入结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆