静态泛型类作为字典

SLa*_*aks 17 .net c# generics clr dictionary

泛型类中的静态字段将为每个泛型参数组合具有单独的值.因此它可以用作Dictionary <Type,无论 >

这是不是一个静态的字典更好或更坏<类型,无论 >?

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

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

要么,

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>() { /*...*/ }
}
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 13

我喜欢这种方式使用泛型类型.特别是,我经常有私有嵌套泛型类用于此目的.

我喜欢它的主要原因是,鉴于类型初始化的工作方式,很难不以这种方式(在线程安全性方面)获得初始化.唯一的问题是如果初始化失败该怎么办 - 偶尔我会使用记住异常来获得第一次必要的访问权限,但这种情况非常罕见.

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