デフォルトのコンストラクターを使用してオブジェクトの作成を制限したい。私は以下のようなデザインを持っているので:
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
ますが、デフォルトのコンストラクターがデザインを台無しにしています....
私は何をすべきか?