【发布时间】:2014-09-22 09:06:06
【问题描述】:
假设 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 的定义是多余的:Person 的KeyType 是int 的事实已明确说明,尽管可以从Person 是@987654328 的子类型这一事实推断出@。
如果能够像这样定义IPersonRepository 那就太好了:
interface IPersonRepository : IRepository<Person> { ... }
让编译器找出KeyType 是int。有可能吗?
【问题讨论】:
-
它应该如何知道
KeyType?你能展示你所期望的完整语法吗?您的最后一个接口定义看起来不完整。 -
我假设最后一行代码应该是
interface IPersonRepository : IRepository<Person> { ... } -
现在尝试在您的
IPersonRepository中编写Get方法,而不必在其中硬编码int,您会意识到这个提议没有太多好处。 -
当然没有找到 KeyType:你没有在你的接口定义中声明它。
-
我想知道为什么人们试图让一切都通用。具有通用键类型的通用实体的通用存储库... 抽象的抽象使生活变得非常复杂。我认为重用在我们的行业中被高度高估了。
标签: c# generics type-inference