开发者

Using an abstract generic class in a dictionary as value without being specific about the type

开发者 https://www.devze.com 2023-01-14 03:40 出处:网络
Maybe a stupid question but when I have an abstract generic class, say A<T>, and I want to build a dictionary with the abstract class as value and some other type as key in a completely differen

Maybe a stupid question but when I have an abstract generic class, say A<T>, and I want to build a dictionary with the abstract class as value and some other type as key in a completely different class. How do I do that without specifying th开发者_Python百科e type?

Dictionary<int, A<T>> dictionary doesn't compile of course.


2 possibilities, I would think:

  • Make the class that hosts the dictionary generic as well and let the type argument "trickle through"
  • Find a non-generic interface under which you can store the instances in the dictionary.


You can only do this if the type parameter has been defined for the class holding the dictionary. In other words, at compile time, the type of T is known.

So this will compile:

public class MyDictionaryWrapper<T>
{
   private Dictionary<int, A<T>> myDict;
}


Can you define a non-generic abstract or interface that all A<T> will implement? This was our solution to a similar problem in our project; we had web control ancestors that were generic to any of our domain classes, so the domain class could be passed in as the DTO and bound/unbound by the control's codebehind. The descendants closed the generic specification, but that ancestor had to stay open, so to allow for collections of these controls independent of domain type, we extracted a non-generic base class from the generic base. Defining an interface would work similarly.


I worked around it by just storing a Type as the value and then work with that Type. Seemed like a cleaner solution.


I think I have to give up type safety in this case and remove the generic. I can't define a non-generic interface because the main method of this class receives an argument of the generic type and I can't make the containing class a generic one either.

However, since this method is currently the only one that has anything to do with the generic class I'm going to remove the generic and make the argument in the method of type object to workaround the problem. I'm going to have to check the type at the callers of this method.

0

精彩评论

暂无评论...
验证码 换一张
取 消