我有一个对象Contact
,它存储在磁盘上。
使用 Contact contact = new Contact("1234")
创建联系人对象后,它会自动从磁盘加载:
class Contact
{
public Contact(string id)
{
Node? testNode = NodeInterface.FileManager.LoadNode(id);
if (testNode != null)
{
LoadContact((Node) testNode);
}
else
{
throw new Exception("Contact does not exist on Disk!");
}
}
public string Name {get; set;}
public string Address {get; set;}
/* ... */
}
现在我可以通过以下方式初始化联系人:
Contact contact1 = new Contact("1234");
Contact nullContact1;
Contact nullContact2 = null;
是否可以用某些内容替换构造函数中引发异常的行,以使结果为空?
Contact nullContact1 = new Contact("thisIdDoesNotExist");
Contact nullContact2 = null;
最佳答案
调用new Contact
将始终导致创建Contact
对象或引发异常。没有办法让构造函数“返回”null
。
但是,您可以将此逻辑移至另一个类并使用工厂设计模式:
public class ContactFactory
{
public static CreateContact(string id)
Node? testNode = NodeInterface.FileManager.LoadNode(id);
if (testNode != null)
{
return new Contact(testNode)
}
else
{
return null;
}
}
class Contact
{
public Contact(Node idNode)
{
LoadContact(idNode);
}
public string Name {get; set;}
public string Address {get; set;}
/* ... */
}
关于c# - 我可以用 null 初始化一个对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70753548/