当变量的值改变时如何触发事件? [英] How to trigger event when a variable's value is changed?

查看:21
本文介绍了当变量的值改变时如何触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 Visual Studio 在 C# 中创建应用程序.我想创建一些代码,以便当变量的值为 1 时执行某段代码.我知道我可以使用 if 语句,但问题是值将在异步过程中更改,因此从技术上讲,可以在值更改之前忽略 if 语句.

I'm currently creating an application in C# using Visual Studio. I want to create some code so that when a variable has a value of 1 then a certain piece of code is carried out. I know that I can use an if statement but the problem is that the value will be changed in an asynchronous process so technically the if statement could be ignored before the value has changed.

是否可以创建事件处理程序,以便在变量值更改时触发事件?如果是这样,我该怎么做?

Is it possible to create an event handler so that when the variable value changes an event is triggered? If so, how can I do this?

我完全有可能误解了 if 语句的工作原理!任何帮助将不胜感激.

It is completely possible that I could have misunderstood how an if statement works! Any help would be much appreciated.

推荐答案

在我看来,您想创建一个属性.

Seems to me like you want to create a property.

public int MyProperty
{
    get { return _myProperty; }
    set
    {
        _myProperty = value;
        if (_myProperty == 1)
        {
            // DO SOMETHING HERE
        }
    }
}

private int _myProperty;

这允许您在属性值更改时随时运行一些代码.如果你愿意,你可以在这里发起一个活动.

This allows you to run some code any time the property value changes. You could raise an event here, if you wanted.

这篇关于当变量的值改变时如何触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆