C# - 通用的方法,与非泛型方法 [英] C# - generic methods vs. non-generic methods

查看:199
本文介绍了C# - 通用的方法,与非泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点搞不清楚为什么/时,我曾经想用一个通用的方法,因为非泛型方法可以访问反正它包含类的一般成员,并传递通用参数。

I'm a bit confused about why/when I'd ever want to use a generic method since a non-generic method can access the generic members of its containing class and be passed generic arguments anyway.

所以,用罐装的例子,可能忽略了一点(但亮点为什么我问这个问题),我为什么会做这样的:

So, using a canned example that likely misses the point (yet highlights why I'm asking this question), why would I do this:

public class SomeGeneric<T>
{
    public T Swap<T>(ref T a, ref T b)
    {
        T tmp = a;
        a = b;
        b = tmp;
    }
}



over

public class SomeGeneric<T>
{
    public T Swap(ref T a, ref T b)
    {
        T tmp = a;
        a = b;
        b = tmp;
    }
}

这?

或者,真的,为什么我要使用泛型方法的所有的?

Or, really, why would I want to use a generic method at all?

推荐答案

您会通常使用的类型不是泛型泛型方法

You'd typically use a generic method in a type that isn't generic.

例如,看的 可枚举。它定义了大部分的LINQ fucntionaltiy的通用扩展方法,但本身不是通用的。

For example, look at the Enumerable class. It defines the generic extension methods for most of the LINQ fucntionaltiy, but itself isn't generic.

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

You also might want a generic method within a generic type, but only if the generic method used a different generic type specifier.

这可以让你写类似以下内容:

This lets you write something like the following:

 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);
      }
 }



(当然,这是一个有点做作,但确实编译和美孚<正常工作; INT> 比作双击等)

这篇关于C# - 通用的方法,与非泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆