【问题标题】:How can i call JUST ONCE a function when a variable changes its value? c# [duplicate]当变量更改其值时,我如何调用 JUST ONCE 函数? c# [重复]
【发布时间】:2017-10-22 17:47:32
【问题描述】:

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

我认为我必须以某种方式使用属性(并且想知道如何使用属性),但任何帮助都会很棒。

【问题讨论】:

  • 设置一个标志并通过方法/属性更改它?
  • 我投票决定将此问题作为题外话结束,因为互联网上只有无数的 C# 属性示例。
  • 实现 INotifyPropertyChanged
  • 您的 C# 版本没有接口和事件?您应该将重要的细节添加到您的问题中
  • 顺便说一句 if ( !Equals( oldValue, newValue ) ) { doWhatever(); }

标签: c# variables properties getter


【解决方案1】:

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

带有支持字段和自定义设置器的属性

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();
    }
}

输出

【讨论】:

  • 非常感谢!这就是我一直在寻找的答案
  • 太好了,随时标记为已回答! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-23
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多