静态泛型类的词典 [英] Static Generic Class as Dictionary

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

问题描述

在泛型类的静态字段对泛型参数的每个组合的独立价值。因此,它可以用作一个字典&所述;类型,的任何的>

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>

这是好还是坏不是静态字典&LT;类型,任何的&GT;

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

在换言之,其中这些实现的更有效?

In other words, which of these implementations more efficient?

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由泛型类型参数查找静态字段?

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

推荐答案

我喜欢使用泛型这种方式。特别是,我经常有私人嵌套泛型类precisely这一目的。

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

主要的事情,我喜欢它是,它是很难的没有的,以获得正确的初始化这种方式(在线程安全方面),给出的方法类型初始化工作。唯一的问题是,如果初始化失败怎么办 - 。偶尔我使出记住一个例外扔在第一次必要的访问,但这是pretty的罕见

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.

我不喜欢猜测的完全的通过类型参数的CLR如何查找的类型,但我pretty的肯定,它会进行优化,以赫克和背部: )

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天全站免登陆