gpt4 book ai didi

c# - 我应该如何清除通用静态类中的字段?

转载 作者:行者123 更新时间:2023-12-02 01:02:34 25 4
gpt4 key购买 nike

我有一个类是这样的:

public static class Messenger<T>
{
private static readonly Dictionary<string, Delegate> eventTable = new Dictionary<string, Delegate>();
public static void DoSomethingWithEventTable() //Somehow fills eventTable
public static void Clear()
{
eventTable.Clear();
}
}

现在,我调用了DoSomethingWithEventTable在我的程序中的某个地方两次,如下所示:

Messenger<int>.DoSomethingWithEventTable();
Messenger<float>.DoSomethingWithEventTable();

我要清除eventTable对于每个 Messenger<T> 。我该怎么做呢?我应该打电话Clear对于我放入泛型中的每种类型,如下所示:

Messenger<int>.Clear();
Messenger<float>.Clear();

或者做一次这样的傻事就足够了:

Messenger<string>.Clear();

UPD:基本实验表明我应该清除每个使用过的 T 的 Messenger。现在有人可以为这些类提供更好的设计吗?

我现在使用的更详细版本:

static public class Messenger<T>
{
private static readonly Dictionary<string, Delegate> eventTable = new Dictionary<string, Delegate>();

static public void AddListener(string eventType, Callback<T> handler)
{
// Obtain a lock on the event table to keep this thread-safe.
lock (eventTable)
{
// Create an entry for this event type if it doesn't already exist.
if (!eventTable.ContainsKey(eventType))
{
eventTable.Add(eventType, null);
}
// Add the handler to the event.
eventTable[eventType] = (Callback<T>)eventTable[eventType] + handler;
}
}

static public void RemoveListener(string eventType, Callback<T> handler)
{
// Obtain a lock on the event table to keep this thread-safe.
lock (eventTable)
{
// Only take action if this event type exists.
if (eventTable.ContainsKey(eventType))
{
// Remove the event handler from this event.
eventTable[eventType] = (Callback<T>)eventTable[eventType] - handler;

// If there's nothing left then remove the event type from the event table.
if (eventTable[eventType] == null)
{
eventTable.Remove(eventType);
}
}
}
}

static public void Invoke(string eventType, T arg1)
{
Delegate d;
// Invoke the delegate only if the event type is in the dictionary.
if (eventTable.TryGetValue(eventType, out d))
{
// Take a local copy to prevent a race condition if another thread
// were to unsubscribe from this event.
Callback<T> callback = (Callback<T>)d;

// Invoke the delegate if it's not null.
if (callback != null)
{
callback(arg1);
}
}
}

static public void Clear()
{
eventTable.Clear();
}
}

我还有另一门课也很重要Messenger (非通用,是的)和 Messenger<T,M> ,也许有一天我什至需要像 Messenger<T,M,N> 这样的东西等

最佳答案

每个Messenger<T> type 将有它自己的 eventTable 副本,因此您需要为您使用的每个不同的 T 调用 Clear()。

如本次测试所示:

[TestFixture]
public class Tests
{
static class MyClass<T>
{
public static List<int> Member = new List<int>();
}

[Test]
public void StaticTest()
{
var m1 = MyClass<int>.Member;
var m2 = MyClass<string>.Member;

Assert.AreNotSame(m1, m2);
}
}

关于c# - 我应该如何清除通用静态类中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13082007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com