简体   繁体   English

在C#中,为什么在这种情况下使用字段与自动实现的属性会导致不同的行为?

[英]In C#, why does using a field vs. an auto-implemented property cause different behavior in this case?

Take the following code from http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx : http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx中获取以下代码:

using System;

struct MutableStruct
{
    public int Value { get; set; }

    public void SetValue(int newValue)
    {
        Value = newValue;
    }
}

class MutableStructHolder
{
    public MutableStruct Field;
    public MutableStruct Property { get; set; }
}

class Test
{    
    static void Main(string[] args)
    {
        MutableStructHolder holder = new MutableStructHolder();
        holder.Field.SetValue(10);
        holder.Property.SetValue(10);

        Console.WriteLine(holder.Field.Value);
        Console.WriteLine(holder.Property.Value);
    }
}

(There were a couple of comments in the code I missed earlier or didn't read that I've taken out now.) (我之前错过的代码中有一些注释,或者没有读到我现在取出的代码。)

The claim on the article is that the output is 10 for holder.Field , but 0 for holder.Property , and this has been verified to be accurate. 物品上的权利要求是,输出是10holder.Field ,但0holder.Property ,这已被证实是准确的。 I'm having a bit of trouble seeing why though. 我很难理解为什么。 An auto-implemented property will have one specific field set aside that it's mapped to, and due to being a struct, Property will immediately have had its backing field fully set and constructed from the beginning. 自动实现的属性将保留一个特定的字段,该Property将被映射到该字段,并且由于它是一个结构,因此Property将立即从一开始就完全设置并构造其后备字段。 What's the difference? 有什么不同?

The line holder.Property returns a copy of MutableStruct . 该生产线holder.Property返回的副本MutableStruct So when you write holder.Property.SetValue(10) you are changing the copy, not the original. 因此,当您编写holder.Property.SetValue(10)您将更改副本,而不是原始副本。

The line holder.Field is an alias for the MutableStruct itself. holder.FieldMutableStruct本身的别名。

It is really hard to not accidentally make copies of structs. 确实很难不偶然地复制结构。 Thus we try to not make them mutable. 因此,我们试图使它们不可变。

The difference is the interjection of a getter for the property. 区别在于该属性的吸气剂插入。 It's functionally equivalent to 它在功能上等同于

private MutableStruct _Property;
public MutableStruct GetProperty()
{
    return _Property;
}
public void SetProperty(MutableStruct value)
{
    _Property = value;
}

So when you call 所以当你打电话

holder.Field.SetValue(10);

you are mutating the struct at Field directly , but when you call 您正在直接Field处更改结构,但是当您调用

holder.Property.SetValue(10);

you are mutating the copy of the struct returned from GetProperty . 您正在变异从GetProperty返回的结构的副本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM