作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我对为什么/何时想要使用泛型方法感到有点困惑,因为非泛型方法可以访问其包含类的泛型成员,并且无论如何都可以传递泛型参数。
因此,使用一个可能没有捕获要点的固定示例(但强调了我为什么要问这个问题),我为什么要这样做:
public class SomeGeneric<T>
{
public T Swap<T>(ref T a, ref T b)
{
T tmp = a;
a = b;
b = tmp;
}
}
结束
public class SomeGeneric<T>
{
public T Swap(ref T a, ref T b)
{
T tmp = a;
a = b;
b = tmp;
}
}
这个?
或者,实际上,为什么我要根本使用泛型方法?
最佳答案
您通常会在非泛型类型中使用泛型方法。
例如,查看 Enumerable
class .它为大多数 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);
}
}
(诚然,这有点做作,但与 Foo<int>
等相比,double
可以正确编译和工作)
关于C# - 泛型方法与非泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13959392/
我是一名优秀的程序员,十分优秀!