C# 自动属性 ​​- += 之后仍然为 null?

发布于 2024-08-02 18:50:14 字数 531 浏览 3 评论 0原文

这对我来说似乎是一个错误......

我接受自动属性,定义如下:

public decimal? Total { get; set; }

首次访问时将为空。它们还没有被初始化,所以它们当然是空的。

但是,即使通过 += 设置了它们的值,这个小数呢?仍然为空。所以之后:

Total += 8;

Total 仍然为 null。这怎么可能是正确的呢?我知道它正在执行 (null + 8),但似乎很奇怪,它没有意识到这意味着它应该设置为 8...

附录:

我在问题中提出了“null + 8”点 -但请注意它适用于字符串。因此,它可以很好地执行 null +“hello”,并返回“hello”。因此,在幕后,它正在将字符串初始化为值为“hello”的字符串对象。 IMO,其他类型的行为应该相同。这可能是因为字符串可以接受 null 作为值,但是 null 字符串仍然不是初始化的对象,对吗?

也许只是因为字符串不能为空......

This seems like a bug to me...

I accept that automatic properties, defined as such:

public decimal? Total { get; set; }

Will be null when they are first accessed. They haven't been initialized, so of course they are null.

But, even after setting their value through +=, this decimal? still remains null. So after:

Total += 8;

Total is still null. How can this be correct? I understand that it's doing a (null + 8), but seems strange that it doesn't pick up that it means it should just be set to 8...

Addendums:

I made the "null + 8" point in my question - but notice that it works with strings. So, it does null + "hello" just fine, and returns "hello". Therefore, behind the scenes, it is initializing the string to a string object with the value of "hello". The behavior should be the same for the other types, IMO. It might be because a string can accept a null as a value, but still, a null string is not an initialized object, correct?

Perhaps it's just because a string isn't a nullable...

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

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

发布评论

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

评论(10

行雁书 2024-08-09 18:50:14
public decimal? Total { get; set; }

null 视为“未知值”。如果您有未知数量的某物,并且您又添加了 8 个,那么您现在有多少?

答:未知。

对可为空变量的操作

在某些情况下,对未知值进行操作会得到已知结果。

public bool? State { get; set; }

以下语句具有已知解决方案,即使它们包含未知值:

State = null;
nextState = State & false;         // always equals false
nextState = State & true;          // still unknown (null)

nextState = State | true;          // always true
nextState = State | false;         // still unknown (null)

看到模式了吗?

当然,如果您希望Totalnull时等于0,则可以使用null合并运算符并编写如下内容:

Total = (Total ?? 0) + 8;

这将在方程中使用Total的值除非它是null,在这种情况下它将使用值 0。

public decimal? Total { get; set; }

Think of null as "unknown value". If you have an unknown quantity of something and you add 8 more, how many do you have now?

Answer: unknown.

Operations on Nullable Variables

There are cases where operations on unknown values give you knowable results.

public bool? State { get; set; }

The following statements have knowable solutions even though they contain unknown values:

State = null;
nextState = State & false;         // always equals false
nextState = State & true;          // still unknown (null)

nextState = State | true;          // always true
nextState = State | false;         // still unknown (null)

See the pattern?

Of course, if you want Total to be equivalent (equal) to 0 when it is null, you can use the null coalescing operator and write something like this:

Total = (Total ?? 0) + 8;

That will use the value of Total in your equation unless it is null, in which case it will use the value 0.

花之痕靓丽 2024-08-09 18:50:14
Null + 8 = Null

您需要先将其设置为零。

Null + 8 = Null

You'll need to set it with zero before.

一个人的夜不怕黑 2024-08-09 18:50:14

null 表示未知值,

unknown value + known value = still unknown value

null means unknown value,

unknown value + known value = still unknown value
蓝天白云 2024-08-09 18:50:14

这是一个单行代码,用于在第一次调用时初始化它并在之后递增它:

    public void InitializeOrIncrement(decimal value)
    {
        // if Total is null then initialize, otherwise increment
        Total = (Total == null) ? value : Total + value;
    }

    public decimal? Total { get; set; }

Here's a one-liner to initialize it on the first call and increment it afterwards:

    public void InitializeOrIncrement(decimal value)
    {
        // if Total is null then initialize, otherwise increment
        Total = (Total == null) ? value : Total + value;
    }

    public decimal? Total { get; set; }
远昼 2024-08-09 18:50:14

来自 MSDN

当您与
可空类型,如果其中之一的值
可空类型为 null 并且
其他不是,所有比较都会评估
为 false,但 !=(不等于)除外。它
重要的是不要假设
因为一个特定的比较
返回 false,情况相反
返回真。

所以,它按预期工作。

From MSDN:

When you perform comparisons with
nullable types, if the value of one of
the nullable types is null and the
other is not, all comparisons evaluate
to false except for != (not equal). It
is important not to assume that
because a particular comparison
returns false, the opposite case
returns true.

So, it works as intended.

终止放荡 2024-08-09 18:50:14

我知道这样做是有意义的

public decimal? Total { get; set; }

Total = (Total ?? 0) + 8;

,但这样做不是更容易吗:

public decimal Total { get; set; }

Total 的初始值为 0

I know that it makes sense to do

public decimal? Total { get; set; }

Total = (Total ?? 0) + 8;

but wouldnt it just be easier to do :

public decimal Total { get; set; }

initial value of Total is 0

不必了 2024-08-09 18:50:14

正如其他人指出的那样,null 不等于零。尽管从长远来看,将空整数默认为零似乎更方便,但它可能会产生奇怪的结果,直到为时已晚时您才发现。

举一个简单的例子,假设您的一个数据源失败并用空值填充您的结果集。您的计算会将空值视为零并继续生成结果。由于数字仍在不断出现,即使它们可能是错误的,您可能永远不会注意到出现了严重错误。

As other people have pointed out, null is not equal to zero. Although it may seem more convenient for a null integer to default to zero in the long run it is likely to produce weird results that you may not spot until it is too late.

As a quick example, say one of your data feeds fails and populates your result set with nulls. Your calculations will treat the nulls as zeros and continue to produce results. As numbers are still coming out, even though they are likely wrong, you might never notice that something has gone critically wrong.

如梦亦如幻 2024-08-09 18:50:14

设置 Total 的值只是

Total = 8;

我建议阅读 Nullable Types< /a> 了解它们是如何工作的。您可以使用 HasValue 检查该属性是否有值。

来自 MSDN

运算符

预定义的一元和二进制
运算符和任何用户定义的
值类型存在的运算符
也可以由可空类型使用。
这些运算符产生空值
如果操作数为空;否则,
运算符使用包含的值
来计算结果。例如:

int? a = 10;
int? b = null;

a++;         // Increment by 1, now a is 11.
a = a * 10;  // Multiply by 10, now a is 110.
a = a + b;   // Add b, now a is null.

to set the value of the Total is just

Total = 8;

I would recommend reading up on Nullable Types to understand how they work. You can check to see if the property has a value by using HasValue.

From MSDN:

Operators

The predefined unary and binary
operators and any user-defined
operators that exist for value types
may also be used by nullable types.
These operators produce a null value
if the operands are null; otherwise,
the operator uses the contained value
to calculate the result. For example:

int? a = 10;
int? b = null;

a++;         // Increment by 1, now a is 11.
a = a * 10;  // Multiply by 10, now a is 110.
a = a + b;   // Add b, now a is null.
氛圍 2024-08-09 18:50:14

空与零不同。零加八等于八……但是零加八呢?始终为空。就像无穷大加上任何东西仍然是无穷大 - 它是未定义的。

您会发现这对于 null 来说是普遍正确的。每个数据库(至少我曾经使用过的数据库)都会给你相同的结果。

Null isn't the same as zero. Zero plus eight is eight... but null plus eight? Always null. Just like infinity plus anything is still infinity - it's undefined.

You'll find that this is universally true of null. Every database (at least that I've ever worked with) will give you the same result.

寄居者 2024-08-09 18:50:14

公共十进制?总计{得到;放; ?

像这样的东西会起作用吗 如果尚未设置值,则进行某种自动初始化。

public decimal? Total
{
  get { return this.totalValue;}
  set
  { 
     if(totalValue == null) { this.totalValue = 0;}
     this.totalValue = value;
  }
}

private decimal? totalValue;

public decimal? Total { get; set; }

Would something like this work? Some sort of automatic initalization if the value isn't yet set.

public decimal? Total
{
  get { return this.totalValue;}
  set
  { 
     if(totalValue == null) { this.totalValue = 0;}
     this.totalValue = value;
  }
}

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