简体   繁体   English

在C#中监视变量

[英]Monitoring a variable in C#

I am wondering what is the best way to monitor a variable in C#. 我想知道在C#中监视变量的最佳方法是什么。 This is not for debugging. 这不是用于调试。 I basically want the program it self to monitor one of its variable all the time during running. 我基本上希望它自己的程序在运行期间一直监视它的一个变量。 For example. 例如。 I am trying to watch if _a is less then 0; 我想看看_a是否小于0; if it is, then the program stops. 如果是,则程序停止。

 _a = _b - _c; // (_b >= _c) 

So _a ranges within [0 N], where N is some positive int; 所以_a的范围在[0 N]之内,其中N是一些正int; I feel the best is to start a thread that monitors the _a value. 我觉得最好是启动一个监视_a值的线程。 Once it, then I should response. 一旦它,那么我应该回应。 But I have no idea how to implement it. 但我不知道如何实现它。 Any one has any suggestions? 有人有什么建议吗? A short piece of code sample will be highly appreciated. 一小段代码示例将受到高度赞赏。

Instead of trying to monitor the value within this variable, you can make this "variable" a property of your class, or even wrap it's access into a method for setting the value. 您可以将此“变量”设置为类的属性,或者将其访问权限包装到用于设置值的方法中,而不是尝试监视此变量中的值。

By using a property or method, you can inject custom logic into the property setter, which can do anything, including "stopping the program." 通过使用属性或方法,您可以将自定义逻辑注入属性设置器,该设置器可以执行任何操作,包括“停止程序”。

Personally, if the goal was to stop the program, I would use a method: 就个人而言,如果目标是停止该程序,我会使用一种方法:

private int _a;
public void SetA(int value)
{
    if (value < 0)
    { 
        // Stop program?
     }
    _a = value;
}

Then call via: 然后致电:

yourClass.SetA(_b - _c);

The reason I would prefer a method is that this has a distinct, dramatic side effect, and the expectation is that a property setter will be a quick operation. 我更喜欢一种方法的原因是它具有明显的,戏剧性的副作用,并且期望一个属性设置器将是一个快速操作。 However, a property setter would work just as well from a technical standpoint. 但是,从技术角度来看,属性设置器也可以正常工作。

A property could do the same thing: 一个属性可以做同样的事情:

private int _a;
public int A
{
    get { return _a; }
    set
    {
        if (value < 0)
        {
            // Handle as needed
        }

        _a = value;
    }
}

The best way is to encapsulate your variable with a property. 最好的方法是使用属性封装变量。

Using this approach you can extend the setter of your property with custom logic to validate the value, logging of changes of your variable or notification (event) that your variable/property has changed. 使用此方法,您可以使用自定义逻辑扩展属性的setter,以验证值,记录变量的更改或变量/属性已更改的通知(事件)。

 private int _a;

 public int MyA {
  get{
    return _a;
  }
  set {
    _a = value;
  }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM