C#有个??运算符,能用来简化代码逻辑
internal class Tester { public void Test() { AAA aaa = null; AAA bbb = new AAA("bbb"); Console.WriteLine(Test1(aaa, bbb).Name); //bbb Console.WriteLine(Test2(aaa, bbb).Name); //bbb aaa = aaa ?? (new AAA("aaa")); //如果aaa==null,则给aaa赋值new AAA("aaa") Console.WriteLine(Test1(aaa, bbb).Name); //aaa Console.WriteLine(Test2(aaa, bbb).Name); //aaa aaa = aaa ?? (new AAA("xxx")); //如果aaa==null,则给aaa赋值new AAA("xxx") Console.WriteLine(Test1(aaa, bbb).Name); //aaa Console.WriteLine(Test2(aaa, bbb).Name); //aaa } AAA Test1(AAA aaa, AAA bbb) { if (aaa != null) { //aaa为不空时使用aaa return aaa; } return bbb; //否则使用第二个对象bbb } AAA Test2(AAA aaa, AAA bbb) { return aaa ?? bbb; //如果此运算符的左操作数不为null,则此运算符将返回左操作数,否则返回右操作数 } } class AAA { public string Name { get; set; } public AAA(string name) { Name = name; } }
标签:AAA,Name,C#,bbb,运算符,WriteLine,aaa,null From: https://www.cnblogs.com/luludongxu/p/17920849.html