gpt4 book ai didi

c# - 没有默认构造函数的设计

转载 作者:太空狗 更新时间:2023-10-29 19:51:37 27 4
gpt4 key购买 nike

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

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 时,它​​会产生这个错误:未处理的异常:System.InvalidOperationException:ConsoleApplication1.BaseC
las 无法序列化,因为它没有无参数构造函数。

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

我该怎么办?

最佳答案

创建私有(private)默认构造函数

private DerivedClass()
{
// code
}

序列化器将成功调用它,即使它是私有(private)的

关于c# - 没有默认构造函数的设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10088302/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com