簡體   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