无法修改struct成员(Unable to Modify struct Members)

我对编程并不陌生,但是我对C#结构的理解似乎存在漏洞。

任何人都可以解释为什么下面的代码打印出“Dist1:0,Dist2:0”?

struct Distance { public void SetFeet(int feet) { Value = feet; } public void SetMiles(float miles) { Value = (int)(miles * 5280f); } public int GetFeet() { return Value; } public float GetMiles() { return Value / 5280f; } private int Value; } class Distances { public Distance Dist1 { get; set; } public Distance Dist2 { get; set; } } class Program { static void Main(string[] args) { Distances distances = new Distances(); distances.Dist1.SetFeet(1000); distances.Dist2.SetFeet(2000); Console.WriteLine("Dist1: {0}, Dist2: {1}", distances.Dist1.GetMiles(), distances.Dist2.GetMiles()); Console.ReadLine(); } }

I'm not at all new to programming, but there seems to be a hole in my understanding of C# structs.

Can anyone explain why the following code prints out "Dist1: 0, Dist2: 0"?

struct Distance { public void SetFeet(int feet) { Value = feet; } public void SetMiles(float miles) { Value = (int)(miles * 5280f); } public int GetFeet() { return Value; } public float GetMiles() { return Value / 5280f; } private int Value; } class Distances { public Distance Dist1 { get; set; } public Distance Dist2 { get; set; } } class Program { static void Main(string[] args) { Distances distances = new Distances(); distances.Dist1.SetFeet(1000); distances.Dist2.SetFeet(2000); Console.WriteLine("Dist1: {0}, Dist2: {1}", distances.Dist1.GetMiles(), distances.Dist2.GetMiles()); Console.ReadLine(); } }

最满意答案

struct是值类型 - 因此,当您访问distances.Dist1.SetFeet您基本上正在访问副本...例如,请参阅MSDN http://msdn.microsoft.com/en-us/library/aa288471%28v=vs 0.71%29.aspx

[编辑评论后] OTOH,如果你的distances.Dist1 = new Distance ().SetFeet (1000); 并将SetFeet的返回SetFeet从void更改为Distance 。 或者让Distance一个类。

有关如何以预期的方式构建结构的参考,请参阅框架中的DateTime结构 - http://msdn.microsoft.com/en-us/library/system.datetime.aspx [/编辑评论后]

struct are value types - so when you are accessing distances.Dist1.SetFeet you basically are accessing a copy... see for example at MSDN http://msdn.microsoft.com/en-us/library/aa288471%28v=vs.71%29.aspx

[EDIT after comment] OTOH if you do distances.Dist1 = new Distance ().SetFeet (1000); AND change the return of SetFeet from void to Distance it should work. Alternatively make Distance a class.

For a reference on how to build structs in a way that they work as expected see the DateTime struct in the framework - http://msdn.microsoft.com/en-us/library/system.datetime.aspx [/EDIT after comment]

更多推荐