我想限制使用默认构造函数创建对象。因为我有如下设计:
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 时,它会产生这个错误:
Unhandled Exception: System.InvalidOperationException: ConsoleApplication1.BaseC
lass cannot be serialized because it does not have a parameterless constructor.
现在我的设计正在崩溃,因为我需要有Username
,Password
参数,但默认构造函数正在破坏我的设计......
我该怎么办?