繁体   English   中英

如何使用模糊的泛型参数指定C#返回值?

[英]How do I specify a C# return value with an ambiguous generic parameter?

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

我想在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#中是否仍然如此?

在C#中,您还可以使Method成为通用方法,该方法的局部类型参数不同

例如

public interface Bar<C> {
  Foo<T, C> Baz<T>();
}

请参阅MSDN:通用方法

怎么样

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM