我有一個類,它是這樣的:如何清除泛型靜態類中的字段?
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>
等
我沒有看到你在任何地方使用T ...它用於什麼? – LightStriker
該類實際上更大,並且具有類似於'public static void AddListener(string eventType,Callback handler)'的方法',但這確實超出了問題的範圍。 –
@Rafal如果它們不是靜態的,那麼評論會更有意義。但由於它們是靜態的,它們實際上是從靜態成員的角度分離出「類」。 – flindeberg