如何使用多种通用类型?

时间:2016-08-31 20:25:48

标签: c# .net generics

我知道做以下方法会让我回复T.

 public static T SomeMethod<T>(string meh, T paramName)
 {  
    return T;
 }

/// I have come to a situation that I am returning a different type 
/// I have the following mind:
public static T SomeMethod<T>(U paramName)
 {  
     return T;
 }

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

这是你在类型

之间进行转换的方法
class Program
{
    public static T SomeMethod<T>(T paramName)
    {
        return paramName;
    }
    public static U SomeMethod<T, U>(T paramName, Func<T,U> convert)
    {
        return convert(paramName);
    }


    static void Main(string[] args)
    {
        var A=SomeMethod(1033);
        // A = 1033
        var B=SomeMethod(1033, (x) => x.ToString());
        // B = "1033"
    }
}

答案 1 :(得分:1)

您可以在一种类型中使用多个泛型:

string myString = SomeMethod<string,int>(3);

使用它:

{{1}}