Generalization T for List <T> Elements

Sorry, if this question was asked before, I could not find anything like it.

I have an enumerated selection that goes into my class:

public enum OrdinalValue { None = 0, Qualification = 1, Career = 2, Faculty = 3 } 

Based on this enumeration, I have 3 property calls that return data from a collection of entities for each of them:

 public List<Qualification> ByQualification { get; set; } public List<Career> ByCareer { get; set; } public List<Faculty> ByFaculty { get; set; } 

I want to create a generic method that returns the correct property based on an enumeration passed back from the calling method, for example:

 public List<T> GetEntities<T>(OrdinalValue ord) { List<T> value = default(List<T>); // based on enum, cast the correct List<T> and return value // something like: if (ord == OrdinalValue.Career) return (List<T>)Convert.ChangeType(this.ByCareer, typeof(T)); return value; } 

Is it possible?

+4
source share
2 answers

It looks like you want something like:

 public List<T> GetEntities<T>(OrdinalValue ord) { object ret; switch(ord) { case OrdinalValue.Career: ret = ByCareer; break; case OrdinalValue.Faculty: ret = ByFaculty; break; case OrdinalValue.Qualification: ret = ByQualification; break; default: throw new ArgumentOutOfRangeException("ord"); } return (List<T>) ret; } 

However, this does not seem like a good design for me. It is hard to suggest anything better without knowing more about the wider picture, but it really does not look like a really general method.

+6
source

I think that @Jon is on the right track, it makes no sense to exaggerate things. When maintaining a method becomes too complicated, you should think about it in a general way.

However, I think his method can be simplified. You do not need to pass the OrdinalValue parameter. Instead of checking, you can check typeof(T) . In any case, the compiler must know T at compile time.

+1
source

Source: https://habr.com/ru/post/1395095/


All Articles