[英]How could I avoid == null checking?
Here is my code which is used widely in project, and I'm wondering can I refactor this somehow so I might avoid == null
checks all the time? 这是我的代码,该代码在项目中广泛使用,我想知道我是否可以以某种方式重构它,以便我可以一直避免
== null
检查?
ActiveCompany = admin.Company == null ? false : admin.Company.Active
Thanks guys 多谢你们
Cheers 干杯
You can use the C# 6: Null-conditional Operator 您可以使用C#6: 空条件运算符
ActiveCompany = admin.Company?.Active == true;
The comparison with true
at the end "converts" the bool?
最后与
true
的比较“转换”了bool?
to bool
. bool
。 You can also use the null coalescing operator to handle the null value as shown by Keith. 您还可以使用空合并运算符来处理空值,如Keith所示。
与null条件链接的null合并运算符对于这种情况很有用:-
ActiveCompany = admin.Company?.Active ?? false
If you find yourself doing this an awful lot, you could write an extension method to simplify the code. 如果您发现这样做非常麻烦 ,则可以编写扩展方法来简化代码。
For example, suppose you have these classes: 例如,假设您具有以下类:
public sealed class Company
{
public bool Active { get; set; }
}
public sealed class MyClass
{
public Company Company;
}
Then you could write an extension method like so: 然后,您可以编写一个扩展方法,如下所示:
public static class MyClassExt
{
public static bool IsActiveCompany(this MyClass myClass)
{
return myClass.Company?.Active ?? false;
}
}
Which would mean you can write code like: 这意味着您可以编写如下代码:
var test = new MyClass();
// ...
bool activeCompany = test.IsActiveCompany();
This doesn't make the code much shorter, but some might think it makes it more readable. 这不会使代码短很多,但是有些人可能认为它使代码更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.