项目中有些对象经常需要重置部分或全部属性到初始状态,想给这些类全部都加上个Reset()方法,又显得太冗余。Q.yuhen的这个Post中提出一种思路,使用默认构造函数来重置状态,这样实现:

class MyClass
{
public int X { get; set; }
public string S { get; set; }
public MyClass()
{
    X = 1234;
    S = "abc";
}
public void Reset()
{
    var ctor = this.GetType().GetConstructor(BindingFlags.Instance | BindingFlags.Public,
     null, new Type[0], null);
    ctor.Invoke(this, null);
}
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
  • 2022-01-09
  • 2022-12-23
  • 2021-10-01
  • 2021-08-04
猜你喜欢
  • 2022-12-23
  • 2021-09-11
  • 2021-07-24
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
相关资源
相似解决方案