【发布时间】:2010-04-12 01:34:32
【问题描述】:
来自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();
// Affects the value of holder.Field
holder.Field.SetValue(10);
// Retrieves holder.Property as a copy and changes the copy
holder.Property.SetValue(10);
Console.WriteLine(holder.Field.Value);
Console.WriteLine(holder.Property.Value);
}
}
1) 为什么要制作(财产的?)副本?
2) 将代码更改为holder.Field.Value 和holder.Property.Value = 10 时,出现以下错误。这让我大吃一惊。
不能修改'MutableStructHolder.Property'的返回值,因为它不是变量
为什么不允许我在属性内赋值!?!两个属性都是get/set!
最后,为什么你会想要 1 和 2 中提到的行为? (它从来没有出现在我身上,我总是使用 get only 属性)。
请解释清楚,我无法想象第二个比第一个少得多。这对我来说太奇怪了。
【问题讨论】:
-
现在您知道为什么可变结构是 C# 中最糟糕的做法了。按值复制和变异的组合并不是一个好的组合。
标签: c# .net properties