无法修改结构成员 [英] Unable to Modify struct Members

查看:41
本文介绍了无法修改结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程一点都不陌生,但我对 C# 结构的理解似乎存在漏洞.

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 the following?

Dist1:0,Dist2:0

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.71%29.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

[评论后编辑]
OTOH 如果您执行 distances.Dist1 = new Distance ().SetFeet (1000); 并将 SetFeet 的返回值从 void 更改为 >距离它应该工作.或者让 Distance 成为一个类.


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.

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

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]

这篇关于无法修改结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆