C# 是否有一种方法来实施和利用;“非空合并”;操作人员

C# 是否有一种方法来实施和利用;“非空合并”;操作人员,c#,.net,null-coalescing-operator,null-coalescing,C#,.net,Null Coalescing Operator,Null Coalescing,在C#中是否有一个notnull合并运算符,在这种情况下可以使用,例如: public void Foo(string arg1) { Bar b = arg1 !?? Bar.Parse(arg1); } 下面的案例让我想到了这一点: public void SomeMethod(string strStartDate) { DateTime? dtStartDate = strStartDate !?? DateTime.ParseExact(strStartDate

C#
中是否有一个notnull合并运算符,在这种情况下可以使用,例如:

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
块中设置值。它似乎更有用

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

只需使用三元:

您建议的运算符实际上并不容易实现,因为它的类型不一致:

DateTime? a = (string)b !?? (DateTime)c;

为了使这个表达式工作,编译器需要在编译时知道
b
为null,这样(null)字符串值就可以分配给
a

Mads Torgersen已经公开表示,下一版本的C#正在考虑使用null传播操作符(但也强调,这并不意味着它会存在)。这将允许以下代码:

var value = someValue?.Method()?.AnotherMethod();
其中,
?。
返回
null
如果操作数(在左侧)是
null
,则else将计算右侧。我怀疑这将为您提供很多方法,尤其是与(比如)扩展方法相结合时;例如:

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
);

为什么不使用just?@Zefnus您不能在现有语言中添加新运算符。如果您想让它设计并创建您自己的语言,请使用kardeşim。@Zefnus否,
运算符是“使用第一个非空表达式”的语法糖;也可以在conditional中表示,但这并不意味着
是conditional的语法糖,尽管“采用第一个空表达式”正在考虑中(至少就成员访问而言)对于C#6,请参见我的回答与此主题类似的一些其他问题:,。这就是答案,谢谢。我考虑了您现在的建议,作为使用条件运算符的替代方案。您知道是否考虑了任何因素,而不是只使用将null映射为null的运算符,而使用
foo?。bar:baz
是等效的[但是对于只被计算一次的
foo
)到
foo?foo.bar:baz
?我认为这会使语法更有用,也会使它更接近
?:
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
);