更改另一个类中struct的值

时间:2017-11-08 05:01:04

标签: c# winforms struct

在使用Winform时,我在主GUI类中定义了一个结构,并在另一个类中更改了struct的值。这是我的Program.cs

static class Program {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new App());
    }
}

public struct StructExample {
    public string str1;
    public string str2;
}

主GUI的代码如下:

 public partial class App : Form {

    public StructExample Example = new StructExample();

    public App() {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e) {
        ButtonToClick.Click += (s, evt) => {
            AnotherGUI setWindow = new AnotherGUI(Example);
            setWindow.ShowDialog();
        };
    }
}

AnotherGUI的代码如下:

 public partial class AnotherGUI : Form {
    public StructExample Example;

    public SettingsGUI(StructExample Example) {
        InitializeComponent();
        this.Example = Example;
    }

    private void DoSomething() {
        //Change values in Example
        Close();
    }
}

但我有一个问题,即在关闭AnotherGUI后,Example的值不会发生变化。如何更改ExampleAnotherGUI的{​​{1}}值以用于App

1 个答案:

答案 0 :(得分:0)

Struct是一个值类型,因此如果需要接收方法来修改它,则需要显式传递ref。

  class Program
    {
        static void Main(string[] args)
        {
            var example = new Example() { Name = "Name"};
            Console.WriteLine(example.Name);

            WrongStructModifier(example);
            Console.WriteLine(example.Name);

            CorrectStructModifier2(ref example);
            Console.WriteLine(example.Name);
        }

        static void WrongStructModifier(Example example)
        {
            example.Name = "Modified Name";
        }

        static void CorrectStructModifier2(ref Example example)
        {
            example.Name = "Modified Name";
        }
    }

    struct Example
    {
        public string Name;
    }