在阅读您的评论后,保存和打开对象的序列化版本是您真正想要做的,我提供了这个答案。
Save方法总是一样的:
class Car {
public void Save(String fileName) {
// Serialize the fields of the current instance to the file.
}
}
要从序列化数据初始化新实例,您可以使用构造函数:
class Car {
public void Car(String fileName) {
// Initialize a new instance from the serialized data in the file.
}
}
另一种选择是提供静态工厂方法:
class Car {
public static Car Open(String fileName) {
var car = new Car();
// Initialize the new instance from the serialized data in the file.
return car;
}
}
要点是“打开”方法不是Car实例上的方法。它应该是构造函数或静态方法。然后,您不必“在内部将对象设置为等于引用”(无论如何这是不可能的)。
在某些方面,您在问题中提出的思路类似于基于原型的编程。但是,C# 是一种基于类的语言,而不是基于原型的语言。