C # Inheritance in <T>

ow indicate that T inherits from another class that implements certain methods:

public Class A { public string GetAccessPoint(); public string GetPriorityMap(); } public Class IndexBuilder<T> where T : A { List<string> Go<T>(T obj) { string aPt=obj.GetAccessPoint(); string pMap=obj.GetPriorityMap(); } } 

In other words, I cannot access the GetAccessPoint and GetPriority obj map, although I indicated that it inherits from A.

+4
source share
4 answers

This is because you redefined what T is when you created the general Go method. Since T is defined at the class level, there is no need to redefine it in Go. Try the following:

 public Class IndexBuilder<T> where T : A { List<string> Go(T obj) { string aPt=obj.GetAccessPoint(); string pMap=obj.GetPriorityMap(); } } 
+14
source

You specify an extra <T> in the List<string> Go<T>(T obj) , which overrides T for another type that does not necessarily inherit from A Use List<string> Go(T obj) instead to avoid overriding T

+3
source

As the other answers explained (correctly) , the problem is that you are defining a new <T> in your method.

However, if this is your entire class, you may not need a common class. The following will work fine:

 public Class IndexBuilder { List<string> Go(A obj) { string aPt=obj.GetAccessPoint(); string pMap=obj.GetPriorityMap(); // Create list... } } 

If you just use instances of A directly, there is no need for generics in IndexBuilder .

+1
source

You override T in the class using the T method in Go .

0
source

All Articles