gpt4 book ai didi

c# - 可以接受使用类型作为字典键吗?

转载 作者:太空狗 更新时间:2023-10-29 21:28:02 24 4
gpt4 key购买 nike

我想制作一个最多可以存储一个对象副本的类。存储在这里的所有对象都将共享同一个基类,我希望能够根据它的类型获取一个对象。

到目前为止,我已经提出了这个解决方案,但我觉得我在为字典键使用 Type 时做错了什么。

在多个模块中使用的基类

interface ISessionVariables { }

用于访问的通用单例类示例

public class SessionVariables
{
private object _sync = new object();
private Dictionary<Type, ISessionVariables> _sessionVariables =
new Dictionary<Type, ISessionVariables>;

public T Get<T>()
where T : ISessionVariable, new()
{
lock (_sync)
{
ISessionVariables rtnValue = null;
if (_sessionVariables.TryGetValue(typeof(T), out rtnValue))
return (T)rtnValue;

rtnValue = new T();
_sessionVariables.Add(typeof(T), rtnValue);

return (T)rtnValue;
}
}
}

这样我就可以从各个模块中这样调用它了

SessionVariableSingleton.Get<ModuleASessionVars>().PropertyA;

SessionVariableSingleton.Get<ModuleCSessionVars>().PropertyC;

这是存储这种数据结构的一种可接受的方式吗?或者是否有更好的替代方案,即使用不带 Type 键的列表或字典?

最佳答案

Type作为 key 很好;线程安全是一个问题,但是 - 在很多方面Hashtable更擅长线程场景。但是,由于您使用的是泛型,因此有一个更好的选择:cheat:

class SessionVariables {
static class Cache<T> where T : ISessionVariable, new() {
public static readonly ISessionVariable Value = new T();
}
ISessionVariable Get<T>() where T : ISessionVariable, new() {
return Cache<T>.Value;
}
}

现在是完全线程安全的(没有“返回不同的实例”问题)没有任何字典成本。


编辑主题Hashtable对于乔恩:

Dictionary<TKey,TValue>不保证并发性,因此您需要同步所有访问 - 包括读取,因为另一个执行写入的线程可能会破坏读取器(您可以在示例中强制执行此操作,但与大多数线程竞争一样,它很难重现)。

根据契约(Contract),Hashtable保证它对任何数量的读者都是安全的,加上至多一个作者。来自 MSDN:

Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable.

这意味着您可以执行以下操作:

var val = (SomeType)hash[key];
if(val == null) {
// not there; actually compute / create the value
val = ...
// and store it for the next access
lock(syncLock) {
hash[key] = val; // note: could do double-check here
}
}
return val;

请注意,上面的read 周期不需要任何同步;只有写入 需要同步。还要注意因为 Hashtable使用 object ,当键和值是类(而不是结构)时效果最好。

是的,现在存在并发词典 - 但上面的工作得很好

关于c# - 可以接受使用类型作为字典键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20073673/

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