没有默认构造函数的设计 [英] Design without default constructor
问题描述
我想使用默认构造函数来限制创建对象。因为我有如下的想法:
I want to restrict creating object using default constructor. Because I have a desing like below:
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设置为Serializable时,会产生以下错误:
未处理的异常:System.InvalidOperationException:ConsoleApplication1.BaseC
lass无法序列化,因为它没有无参数的构造函数
This is ok. But when I make BaseClass to Serializable it'll generate this error:
Unhandled Exception: System.InvalidOperationException: ConsoleApplication1.BaseC
lass cannot be serialized because it does not have a parameterless constructor.
现在我的设计正在崩溃,因为我需要有用户名
,密码
参数,但默认构造函数会破坏我的设计....
Now my design is collapsing because I need to have Username
, Password
parameters but default constructor is ruining my design....
我该怎么办?
推荐答案
创建一个私有的默认构造函数
Create a private default constructor
private DerivedClass()
{
// code
}
串行器即使它是私人的
这篇关于没有默认构造函数的设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!