[英]How to properly return T from a generic method while implementing an interface?
我正在解決一個錯誤。 在重新創建以下示例的錯誤時,我能夠確定問題發生的原因。 但是我一直在尋求更好的解決方案。 因此,給出以下程序:
public interface IFoo<T> {
T OutputType(T param);
}
class Foo : IFoo<Foo> {
public virtual Foo OutputType(Foo param) {
Console.WriteLine("foo");
return param;
}
}
class Bar : Foo, IFoo<Bar> {
public virtual Bar OutputType(Bar param) {
Console.WriteLine("bar");
return param;
}
}
class Program {
static void Main(string[] args) {
Bar bar = new Bar();
CallOutputType(bar);
bar.OutputType(bar);
}
static void CallOutputType<T>(T t) where T : Foo {
t.OutputType(t);
}
}
我期望的輸出是:
bar
bar
但是我得到的是:
foo
bar
看到這樣簡化的問題,很明顯Bar.OutputType沒有覆蓋Foo.OutputType 。 我改進該設計的最佳選擇是什么? Bar.OutputType無法覆蓋Foo.OutputType,因為簽名不同。 更改Bar.OutputType的簽名以匹配Foo.OutputType將不起作用,因為這樣Bar不會隱含 IFoo 。
嗯,我不太熟悉這些東西,但不應該這樣:
static void CallOutputType<T>(T t) where T : IFoo<T>
{
t.OutputType(t);
}
當我編譯它時它起作用了。
如何將其添加到Bar類:
public override Foo OutputType(Foo param)
{
return this.OutputType((Bar)param);
}
如何轉換您的接口定義,以便聲明param
的類型以擴展IFoo
?
我第二話說Spencer-當您的通用約束為T:Foo時,它將Bar轉換為Foo,顯然,您可以隨后調用Foo類的OutputType方法。
我不確定您到底想要完成什么,但這會有所幫助嗎?
如果將泛型添加到實現IFoo的對象中,則可以在創建派生對象時指定類型。
public class Foo<TFoo> : IFoo<TFoo>
{
}
//Then you code would allow this...
//Again other then returning Bar both times I am not certain exactly what you are
//wanting to accomplish But specifying the type at create will allow you to return Bar
//even if you created a Foo or a Bar...
class Program {
static void Main(string[] args) {
Foo foo = new Foo<Bar>();
CallOutputType(foo);
foo.OutputType(foo);
}
static void CallOutputType<T>(T t) where T : Foo {
t.OutputType(t);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.