我想限制使用默认构造函数创建对象。因为我有如下设计:
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass("","");
XmlSerializer xml = new XmlSerializer(typeof(BaseClass));
StreamWriter sw = new StreamWriter(File.Create("c:\\test.txt"));
xml.Serialize(sw,bc);
sw.Flush();
sw.Close();
}
}
[Serializable]
public class BaseClass
{
public string UserName, Password;
// I don't want to create default constructor because of Authentication
public BaseClass(string _UserName, string _Password)
{
UserName = _UserName;
Password = _Password;
f_Authenticate();
}
private void f_Authenticate() { }
}
public class DerivedClass:BaseClass
{
public DerivedClass(string _UserName, string _Password) : base(_UserName, _Password)
{
}
}
还行吧。但是当我将 BaseClass 设为可序列化时,它会生成以下错误:Unhandled Exception: System.InvalidOperationException: ConsoleApplication1.BaseC
lass cannot be serialized because it does not have a parameterless constructor.
现在我的设计正在崩溃,因为我需要Username
, Password
参数但默认构造函数正在破坏我的设计......
我应该怎么办?
创建私有默认构造函数
private DerivedClass()
{
// code
}
即使它是私有的,序列化程序也会成功调用它
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)