C# - 泛型方法与非泛型方法

Maj*_*ons 9 c# generics

我有点困惑为什么/何时我想要使用泛型方法,因为非泛型方法可以访问其包含类的泛型成员并且无论如何都要传递泛型参数.

所以,使用一个可能忽略这一点的罐头示例(但突出了我为什么要问这个问题),为什么我会这样做:

public class SomeGeneric<T>
{
    public T Swap<T>(ref T a, ref T b)
    {
        T tmp = a;
        a = b;
        b = tmp;
    }
}
Run Code Online (Sandbox Code Playgroud)

过度

public class SomeGeneric<T>
{
    public T Swap(ref T a, ref T b)
    {
        T tmp = a;
        a = b;
        b = tmp;
    }
}
Run Code Online (Sandbox Code Playgroud)

这个?

或者,真的,为什么我会想使用一个通用的方法,在所有

Ree*_*sey 9

您通常在非泛型的类型中使用泛型方法.

例如,看一下Enumerable课程.它定义了大多数LINQ功能的通用扩展方法,但它本身并不通用.

您还可能需要泛型类型中的泛型方法,但前提是泛型方法使用不同的泛型类型说明符.

这使您可以编写如下内容:

 class Foo<T> where T : IConvertible, IComparable<T>
 {
      int CompareTo<U>(U other) where U : IConvertible
      {
           // Convert to this
           T otherConverted = Convert.ChangeType(other, typeof(T));
           return this.CompareTo(otherConverted);
      }
 }
Run Code Online (Sandbox Code Playgroud)

(当然,这有点做作,但是编译和正常工作以便Foo<int>与a double等比较)