泛型类中的静态字段将为每个泛型参数组合具有单独的值.因此它可以用作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如何通过泛型类型参数查找静态字段?
例如,如果我有两个对象,一个是Monkey类型,另一个是Dog类型,它们都实现了IAnimal,就像这样:
interface IAnimal
{
int numberOfEyes {get; set;}
string name {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情:
Monkey monkey = new Monkey() { numberOfEyes = 7, name = "Henry" };
Dog dog = new Dog();
MyFancyClass.DynamicCopy(monkey, dog, typeof(IAnimal));
Debug.Assert(dog.numberOfEyes == monkey.numberOfEyes);
Run Code Online (Sandbox Code Playgroud)
我想可以用反射创建像MyFancyClass这样的类......任何聪明的人都有想法?
谢谢,斯蒂芬