0

C#:Serializable() 属性是否阻止将类实例传递给另一个表单?

我有以下课程,并正在尝试为我的应用程序构建一个设置模块。但是当我尝试在 settingForm 方法中访问 _configurator 时出现异常:“对象引用未设置为对象的实例”。为什么?

[Serializable()]
public class Config
{
    public Config() { }
    public string ComPort
    {
        get
        {
            return comPort;
        }
        set
        {
            comPort = value;
        }
    }

    private string comPort;

}

public partial class kineticMoldDockUserControl : UserControl
{

    private settingsForm setForm = null; 

    private Config _cf = null;



    public kineticMoldDockUserControl()
    {
        InitializeComponent();

        _cf = new Config();
        _cf.ComPort = "COM12";

    }




    private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
    {



        if (!Application.OpenForms.OfType<settingsForm>().Any())
        {

            setForm = new settingsForm();

            setForm.Show();

            setForm.cf = _cf;


        }



    }


}

public partial class settingsForm : Form
{

    Config _configutor = null;
    public Config cf { get { return _configutor; } set { _configutor = value; } }


    public settingsForm()
    {
        InitializeComponent();

        try
        {
            MessageBox.Show(_configutor.ComPort.GetType().ToString());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

     }

}
4

4 回答 4

4

您的错误与 Serializable 属性无关。问题在于以下代码行:

            setForm = new settingsForm();

            setForm.Show();

            setForm.cf = _cf;

SettingsForm 构造函数正在使用配置器,但您在调用构造函数后对其进行设置。您可以通过构造函数传递配置器来解决您的问题。

于 2010-09-23T13:54:03.057 回答
1

您粘贴的代码不起作用,因为您在settingsForm的构造函数中访问_configurator。

相反,您应该创建一个接受 Config 实例的构造函数。

序列化属性不是您的错误的原因。

于 2010-09-23T13:56:07.933 回答
1

You're trying to display information about the configutor in the constructor, when the cf variable doesn't get set until after you show the form.

于 2010-09-23T13:57:13.843 回答
0

I'm going to go out on a limb and say that's it because you never instantiate your class. Only code I see is:

Config _configutor = null;;

于 2010-09-23T13:56:37.723 回答