C# 泛型方法

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication1
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             
13             //传入int类型OK
14             int a, b;
15             a = 2;
16             b = 3;
17             swap<int>(ref a, ref b);
18             Console.WriteLine("a(2):" + a + ",b(3):" + b);
19             Console.ReadKey();
20             
21             //传入string类型OK
22             /*
23             string a, b;
24             a = "a";
25             b = "b";
26             swap<string>(ref a, ref b);
27             Console.WriteLine("a(a):" + a + ",b(b):" + b);
28             Console.ReadKey();
29              */
30             /*
31             string a;
32             int b;//b定义为int,第34行报错。
33             a = "a";
34             b = 3;
35             swap<string>(ref a, ref b);
36             Console.WriteLine("a(a):" + a + ",b(b):" + b);
37             Console.ReadKey();
38              */
39 
40         }
41         static void swap<T>(ref T a, ref T b)
42         {
43             T temp = a;
44             a = b;
45             b = temp;
46         }
47     }
48 }

 在泛型类中,非泛型方法可以访问类级别类型参数,如下所示:

 

class SampleClass<T>
{
    void Swap(ref T lhs, ref T rhs) { }
}

如果定义采用相同类型参数作为包含类的泛型方法,编译器将生成警告 CS0693,因为在方法范围内为内部 T 提供的参数隐藏了为外部 T 提供的参数。如果需要使用其他类型参数(而不是实例化类时提供的类型参数)来灵活地调用泛型类方法,请考虑为方法的类型参数提供另一个标识符,如下面示例的 GenericList2<T> 中所示。

class GenericList<T>
{
    // CS0693
    void SampleMethod<T>() { }
}

class GenericList2<T>
{
    //No warning
    void SampleMethod<U>() { }
}

使用约束对方法中的类型参数启用更专门的操作。此版本的 Swap<T> 现在名为 SwapIfGreater<T>,它只能与实现 IComparable<T> 的类型参数一起使用。

void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
{
    T temp;
    if (lhs.CompareTo(rhs) > 0)
    {
        temp = lhs;
        lhs = rhs;
        rhs = temp;
    }
}

 

  

  

posted @ 2018-06-13 10:26  言近旨远_ZKY  阅读(120)  评论(0编辑  收藏  举报