我在我们的项目中遇到了一个问题,感到很困惑。我尝试简化它以重现这种效果:
interface IBar { }
class Bar : IBar {}
interface IFoo<T> where T : IBar { }
class Foo<T> : IFoo<T> where T : IBar { }
class Class1
{
public void DoTheFoo<T>(T bar) where T : IBar
{}
public void DoTheFoo<T>(IFoo<T> foo) where T : IBar
{}
public void Test()
{
var bar = new Bar();
var foo = new Foo<Bar>();
DoTheFoo(bar); // works
DoTheFoo<Bar>(foo); // works
DoTheFoo((IFoo<Bar>)foo); // works
DoTheFoo(foo); // complains
}
}
对我来说,这看起来很好,但编译器在最后一个调用上抱怨,因为它尝试执行
DoTheFoo<T>(T bar)
,而不是 DoTheFoo<T>(IFoo<T> foo)
并抱怨参数类型不匹配。
- 当我删除方法
DoTheFoo<T>(T bar)
时,最后一个调用可以正常工作! - 当我将其更改为
DoTheFoo<T>(Foo<T> foo)
时,它可以工作,但我不能使用它
在我们当前的代码中,解决这个问题并不太难。但是,a)这很奇怪,b)我们不能有这两个重载的方法。
是否有一个通用规则可以解释这种行为?是否可能使其工作(除了给方法命名不同的名称之外)?