gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:39:20 25 4
gpt4 key购买 nike

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

因此,使用一个可能没有捕获要点的固定示例(但强调了我为什么要问这个问题),我为什么要这样做:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com