C#意外的属性行为[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我无法理解这段小代码的C#语义。

using System;

namespace Test
{
    struct Item
    {
        public int Value { get; set; }

        public Item(int value)
        {
            Value = value;
        }

        public void Increment()
        {
            Value++;
        }
    }

    class Bag
    {
        public Item Item { get; set; }

        public Bag()
        {
            Item = new Item(0);
        }

        public void Increment()
        {
            Item.Increment();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Bag bag = new Bag();
            bag.Increment();

            Console.WriteLine(bag.Item.Value);
            Console.ReadKey();
        }
    }
}

只需阅读我希望在我的控制台中读取1作为输出的代码。

不幸的是我不明白为什么控制台打印0。

为了解决这个问题我可以

  1. 宣布Itemclass而不是struct
  2. public Item Item { get; set; }转换为public Item Item;

你能解释为什么会出现这种情况以及为什么上述“解决方案”能解决问题?

c# class struct properties
2个回答
2
投票

你不应该使用可变结构,他们可以有奇怪的行为。更改结构值没有任何好处,因为你会立即更改它们copy.Struct是值类型,这就是为什么你的代码没有按预期工作,因为你有设置属性,每次更改它时你实际上改变了副本不是原始值(结构不是引用类型)。

潜在解决方案

  1. 重构属性(因为使用副本)
  2. 使struct成为类
  3. 使你的结构不可变(使用readonly,例如有关更多详细信息,请参阅此topic

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.