加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 是否可以通过输入类型重载泛型方法?

发布时间:2020-12-15 23:33:16 所属栏目:百科 来源:网络整理
导读:简而言之,我希望有一些方法可以实现这种API风格: Repo repo = new Repo();ListCar cars = repo.AllCar();ListTruck trucks = repo.AllTruck(); 我有一个Repo对象,可以从数据库中检索对象.目前它的工作原理如下: Repo repo = new Repo();ListCar cars = rep
简而言之,我希望有一些方法可以实现这种API风格:

Repo repo = new Repo();
List<Car> cars = repo.All<Car>();
List<Truck> trucks = repo.All<Truck>();

我有一个Repo对象,可以从数据库中检索对象.目前它的工作原理如下:

Repo repo = new Repo();
List<Car> cars = repo.Cars.All();
List<Truck> trucks = repo.Trucks.All();

Repo类是:

class Repo {
    List<Car> Cars = new CarRepo();
    List<Truck> Trucks = new TruckRepo();
}

CarRepo和TruckRepo各包含:

interface IRepo<T> {
    List<T> All();
}

class CarRepo : IRepo<Car> {
    List<Car> All() => new List<Car>() { };
}
// Same for TruckRepo

不幸的是,如果我想在这个模式中添加一个新的车辆集合,我需要在Repo对象上创建一个新的列表.在这个人为的例子中,这没什么大不了的,但是这个神 – Repo对象在具有许多子回购的应用程序中可能会变得非常大.我宁愿拥有的是Repo类直接实现All.

这是我最接近的:

interface IRepo<T>
{
    List<T> All<T>();
}

partial class Repo {}

partial class Repo : IRepo<Car>
{
    public List<Car> All<Car>() => new List<Car>() { };
}

partial class Repo : IRepo<Truck>
{
    public List<Truck> All<Truck>() => new List<Truck>() { };
}

// Usage:
Repo repo = new Repo();
List<Car> cars = repo.All<Car>();

这增加了All<> Repo的方法,但由于一些问题我不知道解决方案,它甚至无法编译.

>所有<>为Repo实现两次,因为类型不会影响实际的方法签名
>列表中的第二个T< T>所有< T>是多余的
>在List< Car>中All< Car>,Car只是写T的另一种方式,而不是指实际的Car类

这是我第一次在C#中深入研究适当的泛型 – 这是否可能?

解决方法

这不是要使用的部分类. partial类的具体用法是在多个文件之间拆分类的功能.

在使用泛型时,目的是定义通用的核心功能,然后可以由多种具体类型重用.

因此,您应该为每种类型创建一个新的具体存储库类.

interface IRepo<T>
{
    List<T> All<T>();
}

class CarRepo : IRepo<Car>
{
    public List<Car> All<Car>() => new List<Car>() { };
}

class TruckRepo : IRepo<Truck>
{
    public List<Truck> All<Truck>() => new List<Truck>() { };
}

public class Truck { }
public class Car { }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读