gpt4 book ai didi

c# - 有没有办法实现和使用 "NOT null coalescing"运算符?

转载 作者:太空狗 更新时间:2023-10-30 00:31:55 24 4
gpt4 key购买 nike

C# 中是否有 not null coalescing 运算符,以防万一可以使用,例如:

public void Foo(string arg1)
{
Bar b = arg1 !?? Bar.Parse(arg1);
}

下面这个案例让我想到了:

public void SomeMethod(string strStartDate)
{
DateTime? dtStartDate = strStartDate !?? DateTime.ParseExact(strStartDate, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
}

我可能没有strStartDate 信息,万一它会是null 但如果我有;我始终确信它将采用预期的格式。因此,不是初始化 dtStartDate = null 并尝试 parse 并在 try catch block 中设置值。好像比较有用。

我想答案是否定的(并且没有这样的运算符 !?? 或其他任何东西)我想知道是否有一种方法可以实现这个逻辑,它是否值得,以及它在什么情况下有用。

最佳答案

Mads Torgersen 公开表示正在考虑为下一版本的 C# 添加空值传播运算符(但同时强调这并不意味着它会存在)。这将允许像这样的代码:

var value = someValue?.Method()?.AnotherMethod();

如果操作数(左侧)为 null,则 ?. 返回 null,否则将计算右侧。我怀疑这会给你带来很多帮助,特别是如果与(比如)扩展方法结合使用;例如:

DateTime? dtStartDate = strStartDate?.MyParse();

哪里:

static DateTime MyParse(this string value) {
return DateTime.ParseExact(value, "dd.MM.yyyy",
System.Globalization.CultureInfo.InvariantCulture
);

但是!只需使用扩展方法,您现在就可以做同样的事情:

DateTime? dtStartDate = strStartDate.MyParse();

static DateTime? MyParse(this string value) {
if(value == null) return null;
return DateTime.ParseExact(value, "dd.MM.yyyy",
System.Globalization.CultureInfo.InvariantCulture
);

关于c# - 有没有办法实现和使用 "NOT null coalescing"运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21425422/

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