gpt4 book ai didi

c# - 静态通用类作为字典

转载 作者:可可西里 更新时间:2023-11-01 03:01:02 24 4
gpt4 key购买 nike

泛型类中的静态字段对于泛型参数的每个组合都有一个单独的值。因此它可以用作 Dictionary whatever>

这比静态 Dictionary whatever> 好还是坏?

换句话说,这些实现中哪个更有效?

public static class MethodGen<TParam> {
public static readonly Action<TParam> Method = CreateMethod();
static Action<TParam> CreateMethod() { /*...*/ }
}

或者,

public static class MethodGen {
static readonly Dictionary<Type, Delegate> methods
= new Dictionary<Type, Delegate>();

public static Action<T> GetMethod<T>() {
//In production code, this would ReaderWriterLock

Delegate method;
if(!methods.TryGetValue(typeof(T), out method)
methods.Add(typeof(t), method = CreateMethod<T>());
return method;
}

static Action<T> CreateMethod<T>() { /*...*/ }
}

特别是,CLR 如何通过泛型类型参数查找静态字段?

最佳答案

我喜欢这样使用通用类型。特别是,正是出于这个目的,我经常使用私有(private)嵌套泛型类。

我喜欢它的主要一点是,鉴于类型初始化的工作方式,很难以这种方式正确进行初始化(就线程安全而言)。唯一的问题是如果初始化失败该怎么办 - 偶尔我会求助于记住一个异常以抛出第一次必要的访问,但这种情况很少见。

我不想猜测 CLR 如何通过类型参数查找类型,确切地,但我很确定它会被优化为 heck 和 back :)

关于c# - 静态通用类作为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/686630/

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