[英]How to assign a value of a property to a var ONLY if the object isn't null
In my code, is there a shorthand that I can use to assign a variable the value of a object's property ONLY if the object isn't null? 在我的代码中,是否有一个简写,我可以使用它来为一个对象的属性的值赋值变量,如果该对象不为null?
string username = SomeUserObject.Username; // fails if null
I know I can do a check like if(SomeUserObject != null) but I think I saw a shorthand for this kind of test. 我知道我可以像if(SomeUserObject!= null)那样进行检查,但我想我看到了这种测试的简写。
I tried: 我试过了:
string username = SomeUserObject ?? "" : SomeUserObject.Username;
But that doesn't work. 但这不起作用。
您在第二个语法上略有偏差。
string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;
我认为,你最接近的是:
string username = SomeUserObject == null ? null : SomeUserObject.Username;
In c# 6.0 you can now do 在c#6.0中,您现在可以做到
string username = SomeUserObject?.Username;
username will be set to null if SomeUSerObject is null. 如果SomeUSerObject为null,则username将设置为null。 If you want it to get the value "", you can do
如果你想让它获得值“”,你可以做到
string username = SomeUserObject?.Username ?? "";
这可能就像你将得到的那样接近:
string username = (SomeUserObject != null) ? SomeUserObject.Username : null;
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. :正如其他人所建议的那样,你可能想要考虑Null对象模式,你可以在其中创建一个特殊的静态User
User.NotloggedIn
并在任何地方使用它而不是null。
Then it becomes easy to always do .Username
. 然后总是很容易做
.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. 其他好处:您可以/可以为案例生成不同的异常(null),其中您没有分配变量和(未登录)不允许该用户执行某些操作的情况。
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, ... 您的NotloggedIn用户可以是来自User的派生类,比如NotLoggedIn,它会覆盖方法并抛出未登录时无法执行的操作的异常,例如付款,发送电子邮件,......
As a derived class from User you get some fairly nice syntactic sugar as you can do things like if (someuser is NotLoggedIn) ...
作为来自User的派生类,你会得到一些相当不错的语法糖,因为你可以做像
if (someuser is NotLoggedIn) ...
You're thinking of the ternary operator. 你在考虑三元运算符。
string username = SomeUserObject == null ? "" : SomeUserObject.Username;
See http://msdn.microsoft.com/en-us/library/ty67wk28.aspx for more details. 有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/ty67wk28.aspx 。
它被称为空合并,并执行如下:
string username = SomeUserObject.Username ?? ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.