我有一个对象数组:
object[] 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;
但是我从 typeof(DateTime) 开始遇到以下错误:
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
最佳答案
您可以使用 is
运算符喜欢
具有 C#7 模式匹配功能的解决方案
string strDate = (myArray[pos] is DateTime date) ? date.ToString("dd/MM/yyyy"): string.Empty;
关于c# - 确定对象是否为 DateTime 而非 null 作为三元中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61076230/