c# - 为什么我的数据在我没有改变的时候却在改变?

标签 c# winforms static

<分区>

我正在开发一个 Microsoft Visual C# Form 应用程序,该应用程序将用于创建将进入 RPG 游戏的所有数据。我设计了一个结构并将其全部封装到一个类中,这样我就可以轻松地读取和写入 XML 文件。

在我的主窗体上,我有一个“公共(public)静态”/“全局”变量,我的所有子窗体都可以从中复制信息...操作它需要的...并将该信息发送回它。

例如。我想要多种货币。处理货币的表单仅从全局变量复制货币数据,并且可以自由支配仅操纵该副本。仅当用户单击“应用”或“接受”按钮时,全局变量才应更新以反射(reflect)这些更改。如果单击“取消”按钮,它应该只是关闭表单,并且在处理表单时复制的数据应该被扔到风中。

不幸的是,情况并非如此。每当我更改副本的数据时,它的更改似乎也会反射(reflect)在全局变量上。这里有一个概念我在这里失踪并且不明白。有人请解释。我检查了我的代码,只有那两点数据应该更新。

“主”窗体中的代码

public partial class frmMain : Form
{
    public static RPGDataCollection DATA = new RPGDataCollection();
    public static string FILE = "";

    public frmMain ()
    {
        InitializeComponent();
        FillDefaultData();
    }

    /// <summary>
    /// Sets item info status text.
    /// </summary>
    /// <param name="text">Text to be displayed.</param>
    private void SetItemInfo (string text)
    {
        lblItemInfo.Text = text;
    }

货币形式代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using RPGData.ObjectTypes.DataGroups;

namespace RPGData.EntryForms
{
    public partial class frmCurrencies : Form
    {
        #region Fields

        private List<Currency> datCurrencies = new List<Currency>();
        private string strEntry = "";
        private bool blnGSC = false;
        private bool blnUpperFlag = false;
        private int intIndex = 0;

        #endregion

        #region Constructor

        public frmCurrencies ()
        {
            InitializeComponent();
        }

        #endregion

        #region Events

        private void frmCurrencies_Load (object sender, EventArgs e)
        {
            datCurrencies = frmMain.DATA.Currencies;
            DisplayData();
        }

        private void btnReplace_Click (object sender, EventArgs e)
        {
            intIndex = lstCurrencies.SelectedIndex;
            Currency c = datCurrencies[intIndex];

            if (txtEntry.Text.Trim().Length > 0)
            {
                SetValues();

                c.Name = strEntry;
                c.HandlesGSC = blnGSC;
                c.Amount = 0;

                datCurrencies[intIndex] = c;
            }

            ResetFields();
            DisplayData();
        }

        private void btnCancel_Click (object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click (object sender, EventArgs e)
        {
            if (txtEntry.Text.Trim().Length > 0)
            {
                SetValues();

                Currency c = new Currency();
                c.Name = strEntry;
                c.HandlesGSC = blnGSC;
                c.Amount = 0;

                datCurrencies.Add(c);
            }

            ResetFields();
            DisplayData();
        }

        private void btnRemove_Click (object sender, EventArgs e)
        {
            intIndex = lstCurrencies.SelectedIndex;

            if (intIndex >= 0)
                datCurrencies.RemoveAt(intIndex);

            ResetFields();
            DisplayData();
        }

        private void btnApply_Click (object sender, EventArgs e)
        {
            frmMain.DATA.Currencies = datCurrencies;
        }

        private void btnAccept_Click (object sender, EventArgs e)
        {
            frmMain.DATA.Currencies = datCurrencies;
            this.Close();
        }

        private void lstCurrencies_SelectedIndexChanged (object sender, EventArgs e)
        {
            intIndex = lstCurrencies.SelectedIndex;
            Currency c = datCurrencies[intIndex];

            txtEntry.Text = c.Name;
            chkGSC.Checked = c.HandlesGSC;
        }

        #endregion

        #region Methods

        private void DisplayData ()
        {
            lstCurrencies.Items.Clear();

            for (int i = 0; i < datCurrencies.Count; i++)
            {
                string gsc = "";
                if (datCurrencies[i].HandlesGSC)
                    gsc = "*";
                else
                    gsc = " ";

                lstCurrencies.Items.Add("[ " + gsc + " ] " + datCurrencies[i].Name);
            }
        }

        private void ResetFields ()
        {
            strEntry = "";
            blnGSC = false;

            txtEntry.Text = strEntry;
            chkGSC.Checked = blnGSC;

            txtEntry.Focus();
        }

        private void SetValues ()
        {
            string entry = ToAllUpper(txtEntry.Text);

            strEntry = entry;
            blnGSC = chkGSC.Checked;
        }

        private string ToAllUpper (string str)
        {
            string entry = "";

            for (int i = 0; i < str.Length; i++)
            {
                string c = "";

                if (i == 0)
                    c = str.Substring(0, 1).ToUpper();

                else if (str.Substring(i, 1) == " ")
                {
                    c = " ";
                    blnUpperFlag = true;
                }

                else if (blnUpperFlag)
                {
                    c = str.Substring(i, 1).ToUpper();
                    blnUpperFlag = false;
                }
                else
                    c = str.Substring(i, 1);

                entry += c;
            }

            return entry;
        }

        #endregion
    }
}

如果你能给我任何帮助,帮助我理解可能发生的事情,那就太好了(或者你看到了我没有看到的错误或错误)。

谢谢!

最佳答案

这行代码datCurrencies = frmMain.DATA.Currencies实际上是创建另一个对 frmMain.DATA.Currencies 的引用并且不进行深度复制。

所以您所做的所有更改 - 实际上是在原始对象上进行的。

您必须克隆它(创建深拷贝),而不仅仅是创建额外的引用。

例如,如果您的 Currency是结构(值类型),以下就足够了:

datCurrencies = new List<Currency>(frmMain.DATA.Currencies);

但是如果你的 Currency是类 - 你可以考虑以下方法: 创建 Clone Currency 中的方法类将返回当前对象的克隆,然后填充您的 datCurrencies喜欢:

datCurrencies = new List<Currency>(frmMain.DATA.Currencies.Count);
foreach(var currency in frmMain.DATA.Currencies)
    datCurrencies.Add(currency.Clone());

关于c# - 为什么我的数据在我没有改变的时候却在改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28152851/

相关文章:

c# - c#中list<>和dictionary<>有什么区别

node.js - 如何将静态文件动态服务?

c# - 如何在静态方法中获取 session 变量的值?

c# - 防止数据网格在 C# 中加载 Entity Framework 导航属性

c# - RangeFileContentResult 和带有远程请求的视频流

c# - 如果我们直接将新对象值赋给旧对象,为什么 Linq to sql 无法跟踪更新信息?

c# - 证书的私钥导出为不同的值?

c# - 将右键单击菜单项添加到图片框

c# - 如何检查 TreeView 根节点是否存在子节点

c# - 在一个类中声明静态方法并将其用作另一个类的方法