<T>中的C#继承

Ast*_*arp 4 c# inheritance

要表明T是从实现某些方法的其他类继承的:

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();
   }
}
Run Code Online (Sandbox Code Playgroud)

换句话说,我无法访问obj的GetAccessPoint和GetPriority映射,尽管我表示它是从A继承的.

Chr*_*ain 14

那是因为你重新定义了当你使Go方法通用时的T是什么.由于T是在类级别定义的,因此无需在Go中重新定义它.试试这个:

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