确定对象是否为 DateTime 而不是 null 作为三元中的条件

use*_*552 2 c# .net-4.5 visual-studio-2013

我有一个对象数组:

对象[] myArray

该数组可以包含 int、string、DateTime 数据类型等。

现在我正在尝试检查 myArray 中的对象是否为 DateTime 类型而不是 null,因此我执行以下三元:

string strDate = myArray[pos] != null && myArray[pos].GetType() is typeof(DateTime) ? Convert.ToDateTime(myArray[pos]).ToString("dd/MM/yyyy") : string.Empty;
Run Code Online (Sandbox Code Playgroud)

但是我从 typeof(DateTime) 开始得到以下错误:

只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句

Pra*_*kar 5

您可以使用is运算符

具有 C#7 模式匹配功能的解决方案

string strDate = (myArray[pos] is DateTime date) ? date.ToString("dd/MM/yyyy"): string.Empty;
Run Code Online (Sandbox Code Playgroud)