C#泛型方法返回不同的对象实例

时间:2015-10-14 10:26:49

标签: c# generics inheritance types

我想做这样的事情:

class A  {
   public int attribute1;
}

class B {
   public string attribute2;
}

class C {
   public static List<T> get<T>(Dictionary properties){
       //Here is a loop to create
       //new instances of T and setting attributes
   }
}

//I want something like this
Dictionary<string, obj> aProperties = new Dictionary<string, obj>();
aProperties.Add("attribute1", 5);

Dictionary<string, obj> bProperties = new Dictionary<string, obj>();
bProperties.Add("attribute2", "asdf");

List<A> listA = C.get<A>(aProperties); // new Instance of A with attribute1 = 5

List<B> listB = C.get<B>(bProperties); // new Instance of B with attribute2 = "asdf"

我可以这样做吗?

0 个答案:

没有答案