-3

是否可以U为函数返回值使用不同的通用参数类型(),而T对于本地参数已经有另一种通用参数类型?

我努力了:

private static U someMethod <T,U>(T type1, Stream s)

private static U someMethod <T><U>(T type1, Stream s)

编辑: 我们同意尝试:

private static U someMethod <T,U>(T type1, Stream s)

public static T someMethodParent<T>(Stream stream)
{

   U something = someMethod(type1, stream);  

      ...
}
4

5 回答 5

9

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

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

正如JavaSa在评论中所说,如果无法从用法中推断出实际类型,则需要提供实际类型,因此

private static U someMethodParent<T>(T Type1, Stream s)
{
    return someMethod<T, ConcreteTypeConvertibleToU>(type1, s);
}
于 2012-12-21T12:06:18.133 回答
5

这应该有效。

private static U someMethod<T, U>(T type1, Stream s)
{
   return default(U);
}
于 2012-12-21T12:06:59.640 回答
2

这有效:

private static TOutput someMethod<TInput, TOutput>(TInput from);

看看MSDN

于 2012-12-21T12:07:02.730 回答
1

好的,在阅读了所有评论后,在我看来你有两个选择......

  1. 在 someMethodParent 的主体中明确指定您需要的 someMethod 的返回类型

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

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

两者都在对其他答案的评论中提到,但没有示例。

于 2012-12-21T13:32:32.537 回答
0

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

public static T someMethodParent<T, U>(T type1, Stream stream)

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

{
    U something = someMethod<T, U>(type1, stream);
    return Default(T);
}
于 2012-12-21T13:04:47.580 回答