gpt4 book ai didi

c# - 确定对象是否为 DateTime 而非 null 作为三元中的条件

转载 作者:行者123 更新时间:2023-12-01 21:43:08 25 4
gpt4 key购买 nike

我有一个对象数组:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com