[英]How do I specify a C# return value with an ambiguous generic parameter?
在C#中,假設我有兩個接口: Foo<in P, out C>
和Bar<C>
。 還假設我有Bar<int>
兩個實現: BarOne
和BarTwo
。
我想在Bar<C>
上添加一個方法Baz()
,該方法返回類似以下內容:
public interface Bar<C> {
// other methods, some of which use C as a type
// then:
Foo<..., C> Baz ();
}
public class BarOne : Bar<int> {
// other methods...
private class FooImplOne : Foo<string, int> {
// stuff here
}
Foo<string, int> Baz() {
return new FooImplOne();
}
}
public class BarTwo : Bar<int> {
// other methods...
private class FooImplTwo : Foo<long, int> {
// stuff here
}
Foo<long, int> Baz() {
return new FooImplTwo();
}
}
但是我不能說Bar
接口的定義中Baz
返回的Foo
的第一個參數。 在Java中,我將使用Foo<?, C>
作為Bar
定義中的返回類型-在C#中我該怎么做?
我找到了一個2008年的stackoverflow答案 ,告訴我“在C#中您不能這樣做,需要為Foo<P, C>
定義一個僅具有通用參數C
的基本接口,然后返回該基本類型”。
在現代的2016 C#中是否仍然如此?
怎么樣
public interface Bar<T1,T2> {
Foo<T1, T2> Baz ();
}
即在兩個Foo類型參數中傳遞
在Java中, <?>
是<? extends Object>
簡寫<? extends Object>
<? extends Object>
。 這意味着試圖使用它的代碼僅知道它是一個對象。 C#中的等效項將僅使用<object>
,因此您的接口將是
Foo<object, C> Baz ();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.