[英]Can I define a custom getter for a C# auto-implemented property (a.k.a. auto backing field)?
[英]In C#, why does using a field vs. an auto-implemented property cause different behavior in this case?
从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);
}
}
(我之前错过的代码中有一些注释,或者没有读到我现在取出的代码。)
物品上的权利要求是,输出是10
为holder.Field
,但0
为holder.Property
,这已被证实是准确的。 我很难理解为什么。 自动实现的属性将保留一个特定的字段,该Property
将被映射到该字段,并且由于它是一个结构,因此Property
将立即从一开始就完全设置并构造其后备字段。 有什么不同?
该生产线holder.Property
返回的副本MutableStruct
。 因此,当您编写holder.Property.SetValue(10)
您将更改副本,而不是原始副本。
行holder.Field
是MutableStruct
本身的别名。
确实很难不偶然地复制结构。 因此,我们试图使它们不可变。
区别在于该属性的吸气剂插入。 它在功能上等同于
private MutableStruct _Property;
public MutableStruct GetProperty()
{
return _Property;
}
public void SetProperty(MutableStruct value)
{
_Property = value;
}
所以当你打电话
holder.Field.SetValue(10);
您正在直接在Field
处更改结构,但是当您调用
holder.Property.SetValue(10);
您正在变异从GetProperty
返回的结构的副本 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.