我已经创建了一个具有默认值的属性的类。在对象生命周期的某个时刻,我希望将对象的属性“重置”回实例化对象时的状态。例如,假设这是一个类:
public class Truck {
public string Name = "Super Truck";
public int Tires = 4;
public Truck() { }
public void ResetTruck() {
// Do something here to "reset" the object
}
}然后,在更改了Name和Tires属性之后,可以调用ResetTruck()方法,并将属性分别重置回"Super Truck“和4。
将属性重置回初始硬编码默认值的最佳方法是什么?
发布于 2009-04-02 05:03:13
您可以在方法中进行初始化,而不是使用声明进行内联。然后让构造函数和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;
}
}另一种方法是根本不使用reset方法。只需创建一个新实例。
发布于 2015-08-15 03:53:01
反射是你的朋友。你可以创建一个帮助器方法,使用Activator.CreateInstance()来设置值类型的默认值,并为引用类型设置' 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.要为您的目的扩展此功能,请拥有私有成员:
//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"};设置构造函数中的值:
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));
}
}稍后重置它们:
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);
}
}发布于 2009-04-02 05:24:22
除非创建对象的开销非常大(而重置并不是出于某种原因)。我认为没有理由实现一个特殊的重置方法。为什么不创建一个具有可用的默认状态的新实例。
重用实例的目的是什么?
https://stackoverflow.com/questions/708352
复制相似问题