c# - 为什么不编译?无法从“X”转换?到“X”
问题描述
我面临一个意想不到的问题(或者这是预期的行为?)。以下代码不编译,它给了我错误:
CS1503 Argument 1: cannot convert from 'long?' to 'long'
public static void Add(long? ticks)
{
if (ticks != null)
{
new DateTime(ticks);
}
}
解决方案
没有从Nullable<T>
to的隐式转换T
- 您可以通过强制转换明确地进行转换,例如new DateTime((long) ticks)
,或使用Value
属性,例如new DateTime(ticks.Value)
.
作为我现在通常更喜欢的替代方案,您可以使用 C# 7 中的模式匹配使其稍微简单一些,在您检查它是否为非空的同一步骤中提取非空值:
public static void Add(long? ticks)
{
// This will match if ticks is non-null, and assign the value
// into the newly-introduced variable "actualTicks"
if (ticks is long actualTicks)
{
var dt = new DateTime(actualTicks);
// Presumably use dt here
}
}
推荐阅读
- progressive-web-apps - 手动卸载 PWA
- amazon-web-services - 如果 CPU 利用率高于 90%,则阻止 AWS EC2 请求/API 调用
- android - 在 Android Studio 北极狐中设置图形编辑器
- amazon-web-services - cognito 用户会话被持久化,而不在本地存储中存储令牌
- reactjs - 实现一个接受一个道具“名称”的功能组件
- powershell - PowerShell System.Net.WebClient 永远不会关闭 ftp 连接
- gcc - GCC GNU -E 代表什么?
- python - Matplotlib 斜体字体不能应用于图例中的数字?
- rust - Rust:TCP Stream 读取 POST 文件在 Edge 或 Chrome 浏览器中效果不佳
- linux - 如何制作 FOR 循环以根据文件扩展名将文件移动到目录