当变量更改其值时,如何调用 JUST ONCE 函数? C#

How can i call JUST ONCE a function when a variable changes its value? c#

假设我有一个 int count,每次它发生变化时我都想调用函数 DoSomething() 我怎么能做吗?

我想我必须以某种方式使用属性(并且想知道如何使用 属性 来做到这一点),但任何帮助都会很棒。

您可以做的一件事是使用 public 属性 来访问 Count,并将 属性 的值存储在私有支持字段中。这样你就可以将setter中传入的value(当有人设置Count 属性时调用)与当前的count进行比较。如果不同,则调用 DoSomething(并更新您的支持字段):

属性 带有支持字段和自定义 setter

private int count = 0;

public int Count
{
    get
    {
        return count;
    }
    set
    {
        // Only do something if the value is changing
        if (value != count)
        {
            DoSomething();
            count = value;
        }
    }
}

示例用法

static class Program
{
    private static int count = 0;

    public static int Count
    {
        get
        {
            return count;
        }
        set
        {
            // Only do something if the value is changing
            if (value != count)
            {
                DoSomething();
                count = value;
            }
        }
    }

    private static void DoSomething()
    {
        Console.WriteLine("Doing something!");
    }

    private static void Main()
    {
        Count = 1; // Will 'DoSomething'
        Count = 1; // Will NOT DoSomething since we're not changing the value
        Count = 3; // Will DoSomething

        Console.WriteLine("\nDone!\nPress any key to exit...");
        Console.ReadKey();
    }
}

输出