静态泛型类作为字典 [英] Static Generic Class as Dictionary

查看:25
本文介绍了静态泛型类作为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这比静态 Dictionarywhatever> 好还是差?

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

public static class MethodGen;{public static readonly Action方法 = CreateMethod();静态动作<TParam>CreateMethod() {/*...*/}}

或者,

公共静态类 MethodGen {静态只读字典<类型,委托>方法= new Dictionary();公共静态动作<T>获取方法(){//在生产代码中,这将 ReaderWriterLock委托方法;if(!methods.TryGetValue(typeof(T), out method)methods.Add(typeof(t), method = CreateMethod());返回方法;}静态动作 TCreateMethod() {/*...*/}}

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

解决方案

我喜欢这样使用泛型类型.特别是,我经常使用私有的嵌套泛型类来实现这一目的.

我最喜欢它的一点是,鉴于类型初始化的工作方式,很难以这种方式正确地进行初始化(就线程安全而言).唯一的问题是如果初始化失败该怎么办 - 偶尔我会想起一个异常来在第一次必要的访问时抛出,但这种情况非常罕见.

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

A static field in a generic class will have a separate value for each combination of generic parameters. It can therefore be used as a Dictionary<Type, whatever>

Is this better or worse than a static Dictionary<Type, whatever>?

In other words, which of these implementations is more efficient?

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

Or,

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>() { /*...*/ }
}

In particular, how does the CLR lookup the static fields by generic type parameter?

解决方案

I like using generic types this way. In particular, I often have private nested generic classes for precisely this purpose.

The main thing I like about it is that it's hard not to get the initialization right this way (in terms of thread safety), given the way type initialization works. The only problem is what to do if initialization fails - occasionally I've resorted to remembering an exception to throw on first necessary access, but that's pretty rare.

I wouldn't like to guess at exactly how the CLR looks up the type via the type arguments, but I'm pretty sure it'll be optimised to heck and back :)

这篇关于静态泛型类作为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆