[英]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.