仅当对象不为 null 时,如何将属性值分配给 var
在我的代码中,是否有一种简写方式,仅当对象不为空时,我才可以使用它来为变量分配对象属性的值?
string username = SomeUserObject.Username; // fails if null
我知道我可以进行像 if(SomeUserObject != null) 这样的检查,但我想我看到了这种测试的简写。
我尝试过:
string username = SomeUserObject ?? "" : SomeUserObject.Username;
但这不起作用。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
在 c# 6.0 中,如果 SomeUSerObject 为 null,您现在可以将
username 设置为 null。
如果你想让它得到值“”,你可以这样做
In c# 6.0 you can now do
username will be set to null if SomeUSerObject is null.
If you want it to get the value "", you can do
第二个的语法有点不对。
Your syntax on the second is slightly off.
我认为,您将得到的最接近的是:
The closest you're going to get, I think, is:
这可能与您将得到的最接近:
This is probably as close as you are going to get:
你可以使用? :正如其他人所建议的,但您可能需要考虑 Null 对象模式,在该模式中创建一个特殊的静态 User
User.NotloggedIn
并在各处使用它而不是 null。然后就可以很容易地始终执行
.Username
。其他好处:您可以在未分配变量的情况(空)和不允许用户执行某些操作(未登录)的情况下生成不同的异常。
您的 NotloggedIn 用户可以是 User 的派生类,例如 NotLoggedIn 会重写方法并在未登录时抛出无法执行的操作的异常,例如付款、发送电子邮件等...
作为 User 的派生类,您会得到一些相当不错的语法糖,因为你可以做类似
if (someuser is NotLoggedIn) ...
的事情You can use ? : as others have suggested but you might want to consider the Null object pattern where you create a special static User
User.NotloggedIn
and use that instead of null everywhere.Then it becomes easy to always do
.Username
.Other benefits: you get / can generate different exceptions for the case (null) where you didn't assign a variable and (not logged in) where that user isn't allowed to do something.
Your NotloggedIn user can be a derived class from User, say NotLoggedIn that overrides methods and throws exceptions on things you can't do when not logged in, like make payments, send emails, ...
As a derived class from User you get some fairly nice syntactic sugar as you can do things like
if (someuser is NotLoggedIn) ...
如果值为 null,此代码将不会分配该属性。当 null 具有“跳过此属性”的特殊含义时,这非常有用。
用法:
This code will not assign the property in case the value is null. This is useful for when null has a special meaning of 'skip this property'.
Usage:
您正在考虑三元运算符。
请参阅 http://msdn.microsoft.com/en-us/library/ty67wk28 .aspx 了解更多详细信息。
You're thinking of the ternary operator.
See http://msdn.microsoft.com/en-us/library/ty67wk28.aspx for more details.
它称为空合并,执行方式如下:
It is called null coalescing and is performed as follows: