为什么只读结构上的突变不会中断

为什么只读结构上的突变不会中断

本文介绍了为什么只读结构上的突变不会中断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,如果你有一个 struct 像这样:

In C#, if you have a struct like so:

struct Counter
{
    private int _count;

    public int Value
    {
        get { return _count; }
    }

    public int Increment()
    {
        return ++_count;
    }
}

你有一个这样的程序:

static readonly Counter counter = new Counter();

static void Main()
{
    // print the new value from the increment function
    Console.WriteLine(counter.Increment());
    // print off the value stored in the item
    Console.WriteLine(counter.Value);
}

程序的输出将是:

1
0

这似乎完全错误.我要么期望输出是两个 1(就像 Counter 是一个 class 或者 struct Counter : ICountercounter 是一个 ICounter) 或者是一个编译错误.我意识到在编译时检测这一点是一件相当困难的事情,但这种行为似乎违反了逻辑.

This seems completely wrong. I would either expect the output to be two 1s (as it is if Counter is a class or if struct Counter : ICounter and counter is an ICounter) or be a compilation error. I realize that detecting this at compilation time is a rather difficult matter, but this behavior seems to violate logic.

这种行为是否有超出实现难度的原因?

Is there a reason for this behavior beyond implementation difficulty?

推荐答案

structs 是值类型,因此具有值类型语义.这意味着每次访问结构体时,您基本上都在使用结构体值的副本.

structs are value types and therefore have a value type sematics. This means each time you access the struct you basically work with a copy of the struct's value.

在您的示例中,您不会更改原始 struct,而只会更改它的临时副本.

In your sample you don't change the original struct but only a temporary copy of it.

请参阅此处了解更多说明:

See here for further explanations:

为什么可变结构是邪恶的

这篇关于为什么只读结构上的突变不会中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:13