gpt4 book ai didi

c# - C# 中的泛型类型推断

转载 作者:太空狗 更新时间:2023-10-29 17:58:12 29 4
gpt4 key购买 nike

假设 C# 中有这些泛型类型:

class Entity<KeyType>
{
public KeyType Id { get; private set; }
...
}

interface IRepository<KeyType, EntityType> where EntityType : Entity<KeyType>
{
EntityType Get(KeyType id);
...
}

以及这些具体类型:

class Person : Entity<int> { ... }

interface IPersonRepository : IRepository<int, Person> { ... }

现在定义PersonRepository是多余的:KeyType 的事实的 Personint是明确说明的,尽管可以从 Person 的事实中推导出来是 Entity<int> 的子类型.

如果能够定义 IPersonRepository 就好了像这样:

interface IPersonRepository : IRepository<Person> { ... }

让编译器计算出 KeyTypeint .可能吗?

最佳答案

不,C# 的类型系统不够先进,无法表达您想要的内容。所需的功能称为higher kinded type,它通常出现在强类型函数语言(Haskell、OCaml、Scala)中。

回到过去,你希望能够写作

interface IRepository<EntityType<EntityKey>> {
EntityType<EntityKey> Get(KeyType id);
}

interface PersonRepository : IRepository<Person> {
Person Get(Int id);
}

但在 C# 中,无法表达 EntityType 的种类,或者换句话说,类型参数具有一些泛型参数并在您的代码中使用该泛型参数。

旁注:存储库模式是邪恶的,必须在火中消亡。

关于c# - C# 中的泛型类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25970274/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com