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);
}
}
}
答案 0 :(得分:4)
您的错误与Serializable属性无关。问题出在下面的代码行中:
setForm = new settingsForm();
setForm.Show();
setForm.cf = _cf;
SettingsForm构造函数使用配置程序,但是在调用构造函数后设置它。您可以通过构造函数传递配置程序来解决您的问题。
答案 1 :(得分:1)
您粘贴的代码不起作用,因为您在settingsForm的构造函数中访问_configurator。
您应该创建一个接受Config实例的构造函数。
序列化属性不是导致错误的原因。
答案 2 :(得分:1)
您尝试在构造函数中显示有关配置程序的信息,而在您显示表单之后,cf变量才会设置。
答案 3 :(得分:0)
我要走出去,说是因为你从未实例化你的课程。我看到的只有代码:
Config _configutor = null;
;