相关疑难解决方法(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
查看次数

如果一个对象的内容具有相同的接口,可以动态地将其复制到另一个对象吗?

例如,如果我有两个对象,一个是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这样的类......任何聪明的人都有想法?

谢谢,斯蒂芬

.net c#

5
推荐指数
3
解决办法
4508
查看次数

标签 统计

.net ×2

c# ×2

clr ×1

dictionary ×1

generics ×1