【问题标题】:C# Unexpected Property Behaviour [duplicate]C#意外的属性行为[重复]
【发布时间】:2017-12-21 11:09:06
【问题描述】:

我看不懂这小段代码的 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. Item 声明为class 而不是struct

  2. public Item Item { get; set; }转换成public Item Item;

您能解释一下为什么会出现这种行为以及为什么上述“解决方案”可以解决问题吗?

【问题讨论】:

  • 来自here - “结构是值类型,类是引用类型。”
  • 类是一种增强的结构类型,它们在其中添加了方法等功能。因此 c# 编译支持结构和类,但使用不同的规则来处理两个不同的对象。您不应该对 Item 类和属性 Item 使用相同的名称。所以正确的解决方案是对 item 使用小写的 'i' : public Item item { get;放; }
  • @jdweng:你测试过吗 - 它仍然打印为零。

标签: c# class struct properties


【解决方案1】:

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

可能的解决方案:

  1. 重构属性(因为使用副本)
  2. 将结构设为类
  3. 使您的结构不可变(使用只读,例如有关更多详细信息,请参阅topic

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2018-01-15
      • 2018-11-29
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 2014-09-25
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      相关资源
      最近更新 更多