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

标签 c# visual-studio-2013 .net-4.5

我有一个对象数组:

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/

相关文章:

c# - 尝试在新的 AppDomain 中加载混合的 C# 和 C++/CLI dll 时,从错误的 AppplicationBase 加载 DLL

c# - .NET 4.5 : internal error in the . NET 运行时 (80131506)/禁用并发 GC

c# - 从 PostCode 获取经度和纬度

c# - DataContractSerializer 创建的 XML 格式

c++ - 如何在没有 lib 文件的情况下将 dll 引用到 Visual Studio

asp.net - 在 Visual Studio 2013 中打开 cshtml 文件时未将对象引用设置为对象的实例

c# - 如何用C#制作受密码保护的文件

c# - Visual C# 2008,读取 XML 文件并填充 listView

c# - 无法将类型 system.collections.generic.IEnumerable<string> 隐式转换为 string[]

c# - 链接 : warning AL1073: Referenced assembly 'mscorlib.dll' targets a different processor