首页 > 解决方案 > 为什么 C# Struct 的行为与属性不同?(与声明为字段相比)

问题描述

我理解 struct 是值类型。但我不明白为什么它会这样?是因为我没有将其视为不可变的吗?还是与 auto 属性有关?

using System;

namespace StructQuestion
{
    class Program
    {
        static StructType structAsProperty { get; set; }
        static StructType structAsField;


        static void Main(string[] args)
        {
            structAsProperty.InjectValue("structAsProperty");
            structAsField.InjectValue("structAsField");

            //debugger says structAsProperty.GetValue() is null
            Console.WriteLine(structAsProperty.GetValue());
            Console.WriteLine(structAsField.GetValue());

            Console.ReadLine();
        }
    }

    public struct StructType
    {
        private string value;
        public void InjectValue(string _value)
        {
            value = _value;
        }
        public string GetValue()
        {
            return value;
        }
    }
}

标签: c#struct

解决方案


让我们看看这个语句中发生了什么:

structAsProperty.InjectValue("structAsProperty");   

我们不必走太远。必须发生的第一件事是解决structAsProperty语句的一部分。这里的关键是理解编译器将属性getset部分重写为幕后的方法调用。

所以我们在这里真正拥有的是对返回结构值的方法的调用。我在这里说“值”而不是“对象”,因为结构是值类型。对于值类型,传递给方法或从方法返回会产生值的副本

现在我们已经足够了解发生了什么。我们调用InjectValue()的是属性结构的副本,而不是属性本身的实例。接下来我们通过它的方法修改这个副本InjectValue()……然后立即忘记这个副本曾经存在过。

你可以像这样修复它:

var prop = structAsProperty; //now we have a variable to keep the result of the implicit get accessor method
prop.InjectValue("structAsProperty");
structAsProperty = prop;

推荐阅读