实现多个通用接口 - 类型错误

Jon*_*nas 4 .net c# generics

我正在尝试做这样的事情:

public interface IRepository<T>
{
  T Get<T>(int id);
}

public interface IFooBarRepository : IRepository<Foo>, IRepository<Bar>
{
}

IFooBarRepository repo = SomeMethodThatGetsTheActualClass();
Foo foo = repo.Get<Foo>(1);
Run Code Online (Sandbox Code Playgroud)

我收到警告:

类型参数"T"与外部类型"IRepository"中的类型参数同名

还有一个错误:

以下方法或属性之间的调用不明确:'IRepository.Get(int)'和'IRepository.Get(int)'

关于如何使这种模式有效的任何想法?

Jon*_*eet 7

要调用适当的方法,您需要让编译器以适当的方式考虑表达式:

IFooBarRepository repo = SomeMethodThatGetsTheActualClass();
IRepository<Foo> fooRepo = repo;
Foo foo = fooRepo.Get(1);
Run Code Online (Sandbox Code Playgroud)

请注意,您可以将其转换为一个语句:

IFooBarRepository repo = SomeMethodThatGetsTheActualClass();
Foo foo = ((IRepository<Foo>)repo).Get(1);
Run Code Online (Sandbox Code Playgroud)

......但这对我来说看起来很难看.

这涉及调用方法.在一个类中实现两个接口是下一个障碍......因为它们在参数方面具有相同的签名.你必须明确地实现其中至少一个 - 如果你同时做到这两点,它可能会减少混淆:

public class FooBarRepository : IFooBarRepository
{
    Foo IRepository<Foo>.Get(int id)
    {
        return new Foo();
    } 

    Bar IRepository<Bar>.Get(int id)
    {
        return new Bar();
    } 
}
Run Code Online (Sandbox Code Playgroud)

编辑:您还需要进行Get非泛型方法:目前你想重新声明的类型参数TIRepository<T>.Get<T>; 你只想使用现有的类型参数IRepository<T>.