在 C# 中,假设我有两个接口(interface):Foo<in P, out C>
和 Bar<C>
.还假设我有两个 Bar<int>
的实现: BarOne
和 BarTwo
.
我想添加一个方法Baz()
在 Bar<C>
返回类似的东西:
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();
}
}
但是关于Foo
的第一个参数我不能说什么在Baz
在 Bar
的定义中返回界面。在 Java 中我会使用 Foo<?, C>
作为 Bar
中的返回类型定义 - 我在 C# 中做什么?
我找到了一个 2008 stackoverflow answer这告诉我“在 C# 中你不能这样做,需要为 Foo<P, C>
定义一个基接口(interface),它只有通用参数 C
并返回该基类型”。
在现代的 2016 C# 中仍然是这种情况吗?
最佳答案
在 C# 中,您还可以使 Method 成为具有该方法本地不同类型参数的泛型方法
例如
public interface Bar<C> {
Foo<T, C> Baz<T>();
}
关于c# - 如何使用不明确的泛型参数指定 C# 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36656014/