相关疑难解决方法(0)

静态泛型类作为字典

泛型类中的静态字段将为每个泛型参数组合具有单独的值.因此它可以用作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如何通过泛型类型参数查找静态字段?

.net c# generics clr dictionary

17
推荐指数
1
解决办法
3074
查看次数

标签 统计

.net ×1

c# ×1

clr ×1

dictionary ×1

generics ×1