仅当对象不为 null 时,如何将属性值分配给 var

发布于 2024-08-28 14:13:56 字数 332 浏览 7 评论 0 原文

在我的代码中,是否有一种简写方式,仅当对象不为空时,我才可以使用它来为变量分配对象属性的值?

string username = SomeUserObject.Username;     // fails if null

我知道我可以进行像 if(SomeUserObject != null) 这样的检查,但我想我看到了这种测试的简写。

我尝试过:

string username = SomeUserObject ?? "" : SomeUserObject.Username;

但这不起作用。

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?

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.

I tried:

string username = SomeUserObject ?? "" : SomeUserObject.Username;

But that doesn't work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

甲如呢乙后呢 2024-09-04 14:13:56

在 c# 6.0 中,如果 SomeUSerObject 为 null,您现在可以将

string username = SomeUserObject?.Username;

username 设置为 null。
如果你想让它得到值“”,你可以这样做

string username = SomeUserObject?.Username ?? "";

In c# 6.0 you can now do

string username = SomeUserObject?.Username;

username will be set to null if SomeUSerObject is null.
If you want it to get the value "", you can do

string username = SomeUserObject?.Username ?? "";
ぇ气 2024-09-04 14:13:56

第二个的语法有点不对。

string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;

Your syntax on the second is slightly off.

string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;
赏烟花じ飞满天 2024-09-04 14:13:56

我认为,您将得到的最接近的是:

string username = SomeUserObject == null ? null : SomeUserObject.Username;

The closest you're going to get, I think, is:

string username = SomeUserObject == null ? null : SomeUserObject.Username;
天冷不及心凉 2024-09-04 14:13:56

这可能与您将得到的最接近:

string username = (SomeUserObject != null) ? SomeUserObject.Username : null;

This is probably as close as you are going to get:

string username = (SomeUserObject != null) ? SomeUserObject.Username : null;
千里故人稀 2024-09-04 14:13:56

你可以使用? :正如其他人所建议的,但您可能需要考虑 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) ...

铁憨憨 2024-09-04 14:13:56

如果值为 null,此代码将不会分配该属性。当 null 具有“跳过此属性”的特殊含义时,这非常有用。

public static void NullGuard<T>(Expression<Func<T>> expression, T? value)
{
    if (expression.Body is not MemberExpression memberExpression)
        throw new ArgumentException("Expression must be a member access expression.");

    var member = memberExpression.Member;

    if (member is not PropertyInfo property)
        throw new ArgumentException("Member must be a property.");

    if (value == null)
    {
        return;
    }

    var constant = Expression.Constant(value);
    var assignment = Expression.Assign(memberExpression, constant);
    var lambda = Expression.Lambda<Action>(assignment);

    lambda.Compile().Invoke();
}

用法:

NullGuard(() => obj.SomeProperty, maybeNullValue);

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'.

public static void NullGuard<T>(Expression<Func<T>> expression, T? value)
{
    if (expression.Body is not MemberExpression memberExpression)
        throw new ArgumentException("Expression must be a member access expression.");

    var member = memberExpression.Member;

    if (member is not PropertyInfo property)
        throw new ArgumentException("Member must be a property.");

    if (value == null)
    {
        return;
    }

    var constant = Expression.Constant(value);
    var assignment = Expression.Assign(memberExpression, constant);
    var lambda = Expression.Lambda<Action>(assignment);

    lambda.Compile().Invoke();
}

Usage:

NullGuard(() => obj.SomeProperty, maybeNullValue);
好听的两个字的网名 2024-09-04 14:13:56

您正在考虑三元运算符。

string username = SomeUserObject == null ? "" : SomeUserObject.Username;

请参阅 http://msdn.microsoft.com/en-us/library/ty67wk28 .aspx 了解更多详细信息。

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.

冰葑 2024-09-04 14:13:56

它称为空合并,执行方式如下:

string username = SomeUserObject.Username ?? ""

It is called null coalescing and is performed as follows:

string username = SomeUserObject.Username ?? ""
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文