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

Dyl*_*ett 8 c# properties class 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
   }
}
Run Code Online (Sandbox Code Playgroud)

然后,在某些时候,后NameTires性质已经改变,该ResetTruck()方法可以称为和属性将被分别重置回"超级卡车"和4.

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

max*_*yfc 15

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

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

   public Truck() {
      Init();
   }

   public void ResetTruck() {
      Init();
   }

   private void Init() {
      Name = "Super Truck";
      Tires = 4;
   }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 在某种程度上,这实际上是我正在做的,但我想知道是否有更好的方法。 (2认同)

arv*_*man 10

反思是你的朋友。您可以创建一个辅助方法来使用 Activator.CreateInstance() 来设置 Value 类型的默认值,并为引用类型设置 'null',但是为什么要在 PropertyInfo 的 SetValue 上设置 null 时会做同样的事情呢?

    Type type = this.GetType();
    PropertyInfo[] properties = type.GetProperties();
    for (int i = 0; i < properties.Length; ++i)
      properties[i].SetValue(this, null); //trick that actually defaults value types too.
Run Code Online (Sandbox Code Playgroud)

为了您的目的扩展此功能,请拥有私人成员:

//key - property name, value - what you want to assign
Dictionary<string, object> _propertyValues= new Dictionary<string, object>();
List<string> _ignorePropertiesToReset = new List<string>(){"foo", "bar"};
Run Code Online (Sandbox Code Playgroud)

在构造函数中设置值:

 public Truck() {
    PropertyInfo[] properties = type.GetProperties();

    //exclude properties you don't want to reset, put the rest in the dictionary
    for (int i = 0; i < properties.Length; ++i){
        if (!_ignorePropertiesToReset.Contains(properties[i].Name))  
            _propertyValues.Add(properties[i].Name, properties[i].GetValue(this));
    }
}
Run Code Online (Sandbox Code Playgroud)

稍后重置它们:

public void Reset() {
    PropertyInfo[] properties = type.GetProperties();
    for (int i = 0; i < properties.Length; ++i){
        //if dictionary has property name, use it to set the property
        properties[i].SetValue(this, _propertyValues.ContainsKey(properties[i].Name) ? _propertyValues[properties[i].Name] : null);     
    }
}
Run Code Online (Sandbox Code Playgroud)


Bri*_*sen 5

除非创建对象真的很昂贵(并且重置不是出于某种原因)。我认为没有理由实施特殊的重置方法。为什么不创建一个具有可用默认状态的新实例。

重用实例的目的是什么?

  • @Dylan:在我看来,当时班级可能做得太多了。查看单一职责原则了解更多信息。 (5认同)