Blazor,运行 静态字符串更改时的非静态函数

Blazor, run non static function when static string change

我有一个带有静态字符串的静态 class,这个字符串被 Javascript 改变了。在(非静态)blazor 组件中检查此字符串更改的最佳方法是什么?

我可以在计时器上设置一个功能 运行,并在进行更改时通知我,这里我还有哪些其他选项?

需要知道静态字符串是否已更改的函数存在于从 ComponentBase 继承的组件中,如果有帮助的话。

只需提及您可以通过利用 Blazor JavaScript 互操作来调用实例 .Net 方法,请查看 following MS documentation.

但是要回答您的问题,正如 Robert 在评论中指出的那样,使用观察者模式或简单的 Event 可以满足您的需求:

static class MyStaticClass
{
    public static EventHandler<string> MyPropertyChanged;

    private static string _myProperty;
    public static string MyProperty
    {
        get => _myProperty;
        set
        {
            if (_myProperty != value)
            {
                _myProperty = value;
                MyPropertyChanged?.Invoke(typeof(MyStaticClass), _myProperty);
            }
        }
    }
}

然后您可以在您的非静态 class:

中订阅此事件
public class MyClass
{
    public MyClass()
    {
        MyStaticClass.MyPropertyChanged += MyPropertyChanged;
    }

    private void MyPropertyChanged(object sender, string e)
    {
        Console.WriteLine($"Changed value is {e}");
    }
}

但是订阅静态 class 事件的问题将是潜在的内存泄漏,如果您的 MyClass 实例不存在于应用程序的整个生命周期中,而静态事件是。查看 Jon Skeet's explanation on this. You can try unsubscribing from the event when you are done with the MyClass instance. Additionally, for a Blazor component, have a look at Component disposal with IDisposable and IAsyncDisposable where you might be able to unsubscribe in the component disposal. You can also try implementing Weak Event Pattern 以解决此问题。