实现多个通用接口-类型错误 [英] Implementing multiple generic interfaces - type error

查看:119
本文介绍了实现多个通用接口-类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下操作:

I'm trying to do something like this:

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);

我收到警告:

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

Type parameter 'T' has the same name as the type parameter from outer type 'IRepository'

还有一个错误:

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

The call is ambiguous between the following methods or properties: 'IRepository.Get(int)' and 'IRepository.Get(int)'

任何关于

推荐答案

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

To call the appropriate one, you'll need to make the compiler think of the expression in the appropriate way:

IFooBarRepository repo = SomeMethodThatGetsTheActualClass();
IRepository<Foo> fooRepo = repo;
Foo foo = fooRepo.Get(1);

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

Note that you could just cast it in one statement:

IFooBarRepository repo = SomeMethodThatGetsTheActualClass();
Foo foo = ((IRepository<Foo>)repo).Get(1);

...但这对我来说看起来很丑。

... but that looks pretty ugly to me.

处理调用方法。 实现一个类中的两个接口是下一个障碍...因为它们在参数方面将具有相同的签名。您必须至少明确实现其中之一-如果同时执行这两种操作,则可能会减少混乱:

That deals with calling the method. Implementing both interfaces in one class is the next hurdle... because they'll have the same signature in terms of parameters. You'll have to implement at least one of them explicitly - and it might cause less confusion if you did both:

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

    Bar IRepository<Bar>.Get(int id)
    {
        return new Bar();
    } 
}

编辑:您还需要将 Get 一个非泛型方法:当前,您正在尝试在 IRepository<中重新声明类型参数 T ; T> .Get< T> ;您只想使用 IRepository< T> existing 类型参数。

You'll also need to make Get a non-generic method: currently you're trying to redeclare the type parameter T in IRepository<T>.Get<T>; you just want to use the existing type parameter of IRepository<T>.

这篇关于实现多个通用接口-类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆