c# - 如何重新初始化或重置类的属性?

标签 c# class properties instantiation

我创建了一个具有默认值属性的类。在对象生命周期的某个时刻,我想将对象的属性“重置”回对象被实例化时的状态。例如,假设这是一个类:

public class Truck {
   public string Name = "Super Truck";
   public int Tires = 4;

   public Truck() { }

   public void ResetTruck() {
      // Do something here to "reset" the object
   }
}

然后在某个时候,在更改了 NameTires 属性之后,可以调用 ResetTruck() 方法并且属性将分别重置回“ super 卡车”和 4。

将属性重置为初始硬编码默认值的最佳方法是什么?

最佳答案

您可以在方法中进行初始化,而不是内联声明。然后让构造函数和重置方法调用初始化方法:

public class Truck {
   public string Name;
   public int Tires;

   public Truck() {
      Init();
   }

   public void ResetTruck() {
      Init();
   }

   private void Init() {
      Name = "Super Truck";
      Tires = 4;
   }
}

另一种方法是根本没有重置方法。只需创建一个新实例即可。

关于c# - 如何重新初始化或重置类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/708352/

相关文章:

python - Pylint 说 : W0233: __init__ method from a non direct base class 'Nested' is called (non-parent-init-called)

c# - 在静态属性 getter 中创建的新对象是否只创建一次?

java - 如何在 JDO(在 Google App Engine 上)中延迟加载属性?

c# - 将角度固定为方向

c# - 如何在 C# 中使用 APNs 授权 key (.p8 文件)?

c# - .NET Core 中的 System.Attribute.GetCustomAttribute

java - Java 中的整数类

angular - 在 Typescript(Angular 5)与 Java 和 C# 中使用类与接口(interface)创建对象

java - 如何显示zk(zul文件)中对象的数据?

c# - 在 Unity3D (C#) 中卡住相机 3 秒