简体   繁体   English

使用 null 合并运算符“??”将自动实现的属性分配给自身

[英]Assigning auto-implemented property to itself with null coalescing operator “??”

I have an auto-implemented property which takes the default value.我有一个自动实现的属性,它采用默认值。 This property reads its value from a database, but if that's null it should take its default value.此属性从数据库中读取其值,但如果是 null,则应采用其默认值。

    // Variable Declaration
    public bool IsSoundEffects { get; set; } = true;

    // Usage
    bool? readFromDB = null;    // Get it from Database assume its NULL
    IsSoundEffects = readFromDB ?? IsSoundEffects;

Is assigning IsSoundEffects to itself a usual practice if a previous database read results in null?如果先前的数据库读取结果为 null,那么将IsSoundEffects分配给自身是一种通常的做法吗?

What should do the trick to make this code organized and readable?应该怎样做才能使这段代码有条理和可读性?

What you are doing is fine.你在做什么很好。 As an alternative, GetValueOrDefault will also work.作为替代方案, GetValueOrDefault也可以使用。

IsSoundEffects = readFromDb.GetValueOrDefault(IsSoundEffects);

Either of these are good solutions if your readFromDb was really a method with parameters because you can have clean syntax such as the below如果您的readFromDb确实是一个带参数的方法,那么这两种方法都是很好的解决方案,因为您可以使用如下所示的简洁语法

IsSoundEffects = readFromDb(some, parameters).GetValueOrDefault(IsSoundEffects);
IsSoundEffects = readFromDb(some, parameters) ?? IsSoundEffects;

The former was your only option prior to the ??前者是您在?? operator being introduced into C#.运算符被引入 C#。

If the "assign to self" is distasteful, then avoid the initial assignment, and do it explicitly elsewhere, eg如果“分配给自己”令人反感,则避免初始分配,并在其他地方明确执行,例如

public bool IsSoundEffects { get; set; }
...
IsSoundEffects = readFromDb(some, parameters).GetValueOrDefault(true);
IsSoundEffects = readFromDb(some, parameters) ?? true;

Make it simple让它变得简单

if(readFromDB != null) IsSoundEffects = readFromDB;

So that you can avoid the assignment of same value when readFromDB is null.这样就可以避免在 readFromDB 为 null 时分配相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM