デフォルトコンストラクタを使用してオブジェクトを作成することを制限したいと思います。私は以下のようなデッサンを持っているので:デフォルトコンストラクタのないデザイン
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する作るとき:私はUsername
、Password
パラメータを持っている必要がありますが、デフォルトコンストラクタは、私のデザインを台無しにされているので Unhandled Exception: System.InvalidOperationException: ConsoleApplication1.BaseC lass cannot be serialized because it does not have a parameterless constructor.
は今、私のデザインが崩れている....
何私はする必要がありますか?
実際にすべての可能性を学びたいと思います。もしあなたが私に何を提供したいのですか? – uzay95
重複しているhttp://stackoverflow.com/questions/267724/why-xml-serializable-class-need-a-parameterless-constructor – Matten