【发布时间】:2013-03-16 08:36:32
【问题描述】:
我对我们项目中的一个问题感到困惑。我试图简化它以重现效果:
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) 太糟糕了。
是否有解释这种行为的通用规则?是否有可能让它工作(除了给方法不同的名字)?
【问题讨论】:
-
我不认为这是重复的。存在通用约束中方法不同的问题。我的方法在声明的参数类型中有所不同。
-
不,这是重复的。仔细阅读我的回答。它解释了为什么重载解析选择它在您的情况下执行的方法。
标签: c# generics overloading