通用类型转换和可分配类型

时间:2017-11-24 12:00:57

标签: c# generics casting

我努力理解并理解使用泛型类型并将其转换为基础形式。下面的代码显示了我所拥有的结构。

{{1}}

我不能将控制器转换为IBaseController,除非它专门实现了BaseRepository的concreate类,而不是其中一个继承类。

使用此示例如果控制器类是SpecificController,我将如何访问BaseRepository方法和属性?

我已经编辑了这个问题,以便更具体地说明我要做的事情。

1 个答案:

答案 0 :(得分:0)

所以我们可以假设filterContext.Controller是你的SpecificController的实例,那么

  1. SpecificController扩展BaseController
  2. BaseController扩展Controller并实现IBaseController(基于类型)
  3. 所以基于引用你的SpecificController可以用作IBaseController
  4. 如果您想在您的泛型规范中使用您的控制器,如IBaseRepository,请使用

    之类的代码
    public class SpecificController : BaseController<IBaseRepository>
    

    在泛型类型代码中您必须定义正确的类型 - 您不能将对象强制转换为父/子。 E.g。

    class Animal { }
    class Dog : Animal { }
    
    List<Dog> dogs = new List<Dog>();
    List<Animal> animals = new List<Animal>();
    
    List<Animal> dogsAsAnimals = dog as List<Animal>; // wrong
    List<Dog> animalsAsDogs = animals as List<Dog>; // wrong
    IList<Animal> newAnimals = animals as IList<Animal>; // correct
    

    最后

    animals.Add(new Dog()); // correct
    

    所以要使用你的代码:

    var _controller = filterContext.Controller as IBaseController<ISpecificRepository>