这里有几个想法:
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace ConsoleApp1
{
public class ServerState
{
public static Action stateChanged;
private Dictionary<string, object> _values = new Dictionary<string, object>();
private void Set(object value, [CallerMemberName] string propertyName = null)
{
_values[propertyName] = value;
stateChanged?.Invoke();
}
private T Get<T>([CallerMemberName] string propertyName = null)
{
if (_values.TryGetValue(propertyName, out var v)) return (T)v;
throw new KeyNotFoundException(propertyName);
}
public string CurrentMap
{
get => Get<string>();
set => Set(value);
}
// You can make them in one line if you want
public string CurrentMap2 { get => Get<string>(); set => Set(value); }
}
public class ServerState2
{
public static Action stateChanged;
private string currentMap;
private void Set<T>(ref T property, T value)
{
property = value;
stateChanged?.Invoke();
}
public string CurrentMap
{
get => currentMap;
set => Set(ref currentMap, value);
}
}
}
如果你想使用多个事件,或者跟踪值是否实际改变,你可以扩展这个想法:
public class ServerState
{
public static Action currentMapChanged;
public static Action currentMap2Changed;
private Dictionary<string, object> _values = new Dictionary<string, object>();
private void Set(object value, Action onChange, [CallerMemberName] string propertyName = null)
{
var previousValue = _values[propertyName];
// Check if value has changed
if (value != previousValue)
{
_values[propertyName] = value;
onChange?.Invoke();
}
}
private T Get<T>([CallerMemberName] string propertyName = null)
{
if (_values.TryGetValue(propertyName, out var v)) return (T)v;
throw new KeyNotFoundException(propertyName);
}
public string CurrentMap
{
get => Get<string>();
// Call `currentMapChanged` if value differs
set => Set(value, currentMapChanged);
}
// You can make them in one line if you want
// Call `currentMap2Changed` if value differs
public string CurrentMap2 { get => Get<string>(); set => Set(value, currentMap2Changed); }
}
此外,您应该考虑使用event 关键字来阻止其他类触发此事件。还要注意静态事件,它们在静态上下文中持有对侦听委托的引用,并且需要注意避免内存泄漏。