Design without default constructor

被刻印的时光 ゝ 提交于 2019-11-30 04:50:30

问题


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)
    {
    }
}

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....

What should I do?


回答1:


Create a private default constructor

private DerivedClass()
{
    // code
}

The serialzer will successfully call this even though it's private




回答2:


The class deserializing your instances requires a parameterless constructor to create the instance, but you don't have to implement a public constructor -- it's enough to have a private or internal constructor as long as it needs no parameters.

By the way, you can as well use the DataContractSerializer, which does not require a parameterless constructor and creates XML, too; it's always my primary choice :-)




回答3:


  • Have you tried to create a private parameterless constructor?

  • If there is the need of a public one, you can always comment saying that it should not be used (not the best solution)

You also need to create properties in your Serializable class. Variables are not considered and will not be read or written during serialization/deserealization process



来源:https://stackoverflow.com/questions/10088302/design-without-default-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!