繁体   English   中英

如何使通用存储库能够自动推断主键的类型?

[英]How to make Generic Repository able to automatically infer the type of primary key?

以下代码已经有效,但我认为在下面指定int

var repo = new Repository<Student, int>(students);

有点多余。 我想简化如下:

var repo = new Repository<Student>(students);

我应该如何修改下面的IRepositoryRepository来实现我想要的?

最小的工作示例:

class Entity<TKey>
{
    public TKey Id { get; set; } = default!;
}


interface IRepository<TEntity, TKey> where TEntity : Entity<TKey>
{
    IEnumerable<TEntity> GetAll();
}

class Repository<TEntity, TKey> : IRepository<TEntity, TKey> where TEntity : Entity<TKey>
{
    private readonly IEnumerable<TEntity> data;
    public Repository(IEnumerable<TEntity> data) => this.data = data;
    public IEnumerable<TEntity> GetAll() => data;
}


class Student : Entity<int>
{
    public string Name { get; set; } = default!;
}

class Program
{
    static void Main()
    {
        var students = new Student[]
        {
           new Student { Name="Andy"},
           new Student { Name="Bob"},
           new Student { Name="Cindy"}
        };

        var repo = new Repository<Student, int>(students);
    }
}

注意:我的实体可以具有类型为stringintGuid等的主键。

c# 不能进行部分类型推断。 在某些情况下,您可以通过创建一个具有一个泛型类型参数的 object 并使用一种可以推断另一个的方法来解决此问题。 但是在这种特定情况下,我看不到任何方法可以做到这一点。

但是您也许可以使用 static 方法来推断两种类型:

public static class Repository{
    public static Repository<TEntity, TKey> Create<TEntity, TKey>(IEnumerable<TEntity> data) 
        where TEntity : Entity<TKey> 
    => new Repository<TEntity, TKey>(data);
}
...
var repo = Repository.Create(students);

这里的问题是构造函数不能进行类型推断,但 static 方法可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM