访问 null 对象的属性时是否有方便的语法返回 null 而不是异常
考虑这个简单的 C# 示例:
var person = new Person {Name = "Fred", MailingAddress=null };
var result = String.Format("{0} lives at {1}",person.Name, person.MailingAddress.Street);
显然这会抛出 NullReferenceException,因为 MailingAddress 属性为 null。
我可以将第二行重写为:
var result = String.Format("{0} lives at {1}", person.Name, person.MailingAddress == null ? (String)null : person.MailingAddress.Street);
有没有更简单的方法来表达这一点?
Consider this simple c# example:
var person = new Person {Name = "Fred", MailingAddress=null };
var result = String.Format("{0} lives at {1}",person.Name, person.MailingAddress.Street);
clearly this will throw a NullReferenceException because the MailingAddress proptery is null.
I could rewrite the second line as:
var result = String.Format("{0} lives at {1}", person.Name, person.MailingAddress == null ? (String)null : person.MailingAddress.Street);
Is there a simpler way to say express this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从技术上讲,此代码违反了德米特定律,因此有些人会认为编写这种形式很糟糕首先。
所以不,没有本地语法来完成你想要的,但是将此代码移动到
Person
类中的属性将使此调用代码更干净,并且还使你符合 demeter 定律。This code is technically a violation of the Law of Demeter, so some would consider it bad form to write this in the first place.
So no, there's no native syntax to accomplish what you want, but moving this code to a property in your
Person
class would make this calling code more clean, and also bring you in line with the law of demeter.实际上没有任何好的语法。合并运算符是其中的一部分,但您需要处理通过 null 进行遍历,而不仅仅是替换 null。您可以做的一件事是为该类提供一个静态“空对象”,例如:
然后您可以像这样使用合并运算符:
如果您想采用扩展方法路线,您可以执行以下操作:
然后你可以这样做:
There's not really any good syntax for this. The coalesce operator is part of it, but you need to handle traversing through a null, not just replacing a null. One thing you could do would be to have a static "null object" for the class, something like:
Then you could use the coalesce operator like so:
If you want to go the extension method route, you could do something like this:
Then you could do:
您可以使用基于表达式树的设备,因此您可以编写
免责声明:我没有编写此代码,我只是不'我也不知道我最初是在哪里找到它的。有人认识这个帮手吗?
You could use a device based on expression trees, so you'd write
Disclaimer: I haven't written this code, I just don't know where I originally found it either. Anyone recognize this helper?
您可以使用此扩展方法:
示例:
You can use this Extension method:
Example: