c# - 如何使用不明确的泛型参数指定 C# 返回值?

标签 c# generics

在 C# 中,假设我有两个接口(interface):Foo<in P, out C>Bar<C> .还假设我有两个 Bar<int> 的实现: BarOneBarTwo .

我想添加一个方法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的第一个参数我不能说什么在BazBar 的定义中返回界面。在 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>();
}

See MSDN: Generic Methods

关于c# - 如何使用不明确的泛型参数指定 C# 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36656014/

相关文章:

c# - C# 2.0 中是否有匿名的、类型安全的、通用的委托(delegate)签名?

c# - 您如何使用 ABCpdf 确定 PDF 文本框字段是否为多行?

c# - 使用 ObjectResult 将 EF6 转换为 EF 核心

c# - 反序列化后 JSON 不保留值

c# - 哈瓦那人的关系

templates - 如何在 Rust 中使用数值作为泛型参数?

c# - 继承通用类的对象列表

c# - 添加带格式的 XML 节点

C# 将比较类作为泛型类型传递

java - 如何重写泛型方法