设计没有默认构造函数

我想使用默认构造函数限制创建对象。 因为我有如下设计:

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.

现在我的设计正在崩溃,因为我需要有UsernamePassword参数但默认构造函数正在破坏我的设计….

我该怎么办?

创建一个私有默认构造函数

 private DerivedClass() { // code } 

串行器即使是私有的,也会成功调用它

反序列化实例的类需要一个无参数构造函数来创建实例,但是您不必实现公共构造函数 – 只要它不需要参数就足以拥有privateinternal构造函数。

顺便说一句,您也可以使用DataContractSerializer ,它不需要无参数构造函数并创建XML; 它总是我的主要选择:-)

  • 您是否尝试过创建私有无参数构造函数?

  • 如果需要一个公共的,你可以随时评论说不应该使用它(不是最好的解决方案)

您还需要在Serializable类中创建属性。 在序列化/去序列化过程中不考虑变量,也不会读取或写入变量