简体   繁体   English

Null C# 5 中的条件运算符

[英]Null Conditional Operator in C# 5

In c# 6, there is the new Null Conditional Operator, like so:在 c# 6 中,有新的 Null 条件运算符,如下所示:

var name = p?.FirstName;

What can we use in c# 5 so that we don't have to resort to:我们可以在 c# 5 中使用什么,这样我们就不必求助于:

var name = null;
if(p != null)
    name = p.FirstName;

Lashane has the same idea I did. Lashane 和我有同样的想法。 Using a conditional operator can save you some time使用条件运算符可以节省一些时间

the basic idea is that you evaluate if something is true or false, and give the values you want to put in for either.基本思想是你评估某事是真还是假,并给出你想要为其中任何一个输入的值。

var name = p != null ? p.FirstName : null;

The above is saying: "If p,= null? conditional (.) set to p,FirstName when true, null when false"上面是说:“如果 p,= null?条件 (.) 设置为 p,FirstName 为真,null 为假”

https://msdn.microsoft.com/en-us/library/zakwfxx4(v=vs.90).aspx https://msdn.microsoft.com/en-us/library/zakwfxx4(v=vs.90).aspx

I has a same idea.我有同样的想法。 And this is what I did:这就是我所做的:

public static T IsNull<T>(this T value) where T : new()
{
    if (value != null)
        return value;
    else
        return new T();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM