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