如何使用两个generics类型参数声明一个Method?

是否可以为函数返回值执行不同的通用参数类型( U ),同时已经为本地参数设置了另一个通用参数类型?

我试过了:

 private static U someMethod (T type1, Stream s) 

 private static U someMethod (T type1, Stream s) 

编辑:我们同意尝试:

 private static U someMethod (T type1, Stream s) public static T someMethodParent(Stream stream) { U something = someMethod(type1, stream); ... } 

private static U someMethod (T type1, Stream s)是一种正确的语法。

http://msdn.microsoft.com/en-us/library/twcad0zb%28v=vs.80%29.aspx

正如JavaSa在评论中所述,如果无法根据用法推断出它们,则需要提供实际类型,因此

 private static U someMethodParent(T Type1, Stream s) { return someMethod(type1, s); } 

这应该工作。

 private static U someMethod(T type1, Stream s) { return default(U); } 

这工作:

 private static TOutput someMethod(TInput from); 

在MSDN上搞定

好的,看完所有评论后,我觉得你有两种选择……

  1. 在someMethodParent的主体中,从someMethod中明确指定所需的返回类型

     public static T someMethodParent(Stream stream) { TheTypeYouWant something = someMethod(type1, stream); ... return Default(T); } 
  2. 在someMethodParent的主体中使用object作为someMethod的返回类型,但是你仍然需要强制转换为可用的类型

     public static T someMethodParent(Stream stream) { object something = someMethod(type1, stream); ... TheTypeYouNeed x = (TheTypeYouNeed) something; // Use x in your calculations ... return Default(T); } 

其中两个在其他答案的评论中提到,但没有例子。

为了在someMethodParent中使用U,必须指定它,就像你在someMethod中所做的那样

 public static T someMethodParent(T type1, Stream stream) 

现在我可以在方法体中使用U作为someMethod的返回类型…

 { U something = someMethod(type1, stream); return Default(T); }