In C#, suppose I have two interfaces: Foo<in P, out C>
and Bar<C>
. Also suppose I have two implementations of Bar<int>
: BarOne
and BarTwo
.
I want to add a method Baz()
on Bar<C>
that returns something like:
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();
}
}
But I can't say anything about the first parameter of Foo
in Baz
's return in the definition of the Bar
interface. In java I'd use Foo<?, C>
as the return type in the Bar
definition - what do I do in C#?
I found a 2008 stackoverflow answer that tells me "In C# you can't do that, and need to define a base interface for Foo<P, C>
that only has the generic parameter C
and return that base type instead".
Is that still the case in modern, 2016 C#?
In C# you would also make the Method a generic method with a different type parameter local to that method
eg
public interface Bar<C> {
Foo<T, C> Baz<T>();
}
how about
public interface Bar<T1,T2> {
Foo<T1, T2> Baz ();
}
ie pass both Foo type params in
In Java, <?>
is shorthand for <? extends Object>
<? extends Object>
. This means that the code that is trying to use it only knows that it is an object. The equivalent in C# would just be using <object>
, so your interface would just be
Foo<object, C> Baz ();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.