泛型类和泛型方法,下面的例子中定义泛型类的原因是什么? [英] generic class and generic method , what would be the reason to define the class a generic class in the below example

查看:115
本文介绍了泛型类和泛型方法,下面的例子中定义泛型类的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间有什么区别吗?如果我只是定义方法,它是否与定义类型T的类相同。

/ p>

  void Main()
{
Test1< int> x = new Test1< int>();
x.Test1Method(1);

Test2 x1 = new Test2();
x1.Test2Method(1);
}

public class Test1< T>
{
public void Test1Method< T>(T x)
{
Console.WriteLine(x);



public class Test2
{
public void Test2Method< T>(T x)
{
Console .WriteLine(X);
}
}


解决方案

它是不一样的,但只有当你有一个泛型类型的属性/字段(只有在类本身是泛型时才可以做)或者你有多个方法时,区别只是显而易见的:

  public class ArrayWrapper< T> {
private T []元素;

public T get(int index){
return elements [index];
}

public void set(int index,T value){
elements [index] = value;


没有< T> T []元素字段不会被编译,并且可以在中使用不同的类型。 get() set()放在同一个对象上。

指出,你可能不希望在类上使用< T> < T>
,因为它在两个地方都会引入另一个通用类型参数的方法是独立于类的...)

Is there any difference between the two. What would be the reason that I define a generic class of type T.

If I just define the methods does it mean the same as defining the class of Type T.

void Main()
{
    Test1<int> x = new Test1<int>();
    x.Test1Method(1);

    Test2 x1 = new Test2();
    x1.Test2Method(1);
}

public class Test1<T>
{
    public void Test1Method<T>(T x)
    {
        Console.WriteLine(x);
    }
}

public class Test2
{
    public void Test2Method<T>(T x)
    {
        Console.WriteLine(x);
    }
}

解决方案

It is not the same, but the difference is only evident when you have properties/fields with a generic type (which you can only do when the class itself is generic) or you have multiple methods:

public class ArrayWrapper<T> {
    private T[] elements;

    public T get(int index) {
        return elements[index];
    }

    public void set(int index, T value) {
        elements[index] = value;
    }
}

Without <T> on the class, the T[] elements field will not compile, and it would be possible to use different types in get() and set() on the same object.

(As Lee pointed out, you probably don't want to use <T> on the methods when you have it on the class, as having it in both places would actually introduce another generic type parameter for the method which is independent of the one for the class...)

这篇关于泛型类和泛型方法,下面的例子中定义泛型类的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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