简体   繁体   English

C#如何使用泛型

[英]C# how to use generic type

I've a type using generics like this 我有一个使用这样的泛型的类型

public class Stack<T> {
    public void MyMethod() ...
}

In another class, I would like to write a method that takes this Stack-type for any T: 在另一个类中,我想编写一个对任何T都采用此Stack-type的方法:

public class MyClass  {
    public void MyMethod(Stack<T> stack) {
        stack.MyMethod();
    }
}

Is that possible? 那可能吗?

Make either the class, or the method, in MyClass generic. 使MyClass的类或方法通用。

Generic class: 通用类:

public class MyClass<T>  {
    public void MyMethod(Stack<T> stack) {
        stack.MyMethod();
    }
}

Generic method: 通用方法:

public class MyClass  {
    public void MyMethod<T>(Stack<T> stack) {
        stack.MyMethod();
    }
}

Which is appropriate depends on the scope in which you want the T to be variable. 哪个合适取决于您希望T可变的范围。 If a single instance of MyClass should be able to call MyMethod with several different types of stacks, then the method should be generic. 如果MyClass的单个实例应该能够使用几种不同类型的堆栈来调用MyMethod ,则该方法应该是通用的。 If a single instance of MyClass should require all calls to MyMethod to pass the same kind of stack, then the whole class should be generic. 如果MyClass的一个实例应要求对MyMethod所有调用都传递相同种类的堆栈,则整个类应是通用的。

Either: 要么:

public class MyClass 
{
  public void MyMethod<T>(Stack<T> stack) 
  {
     stack.MyMethod();
  }
}

or 要么

public class MyClass<T>  
{
  public void MyMethod(Stack<T> stack) 
  {
     stack.MyMethod();
  }
}

is correct. 是正确的。

There are two type of generic : 有两种类型的泛型:

one = generic method 一个=通用方法

two = generic class 两个=通用类

For example : 例如 :

using System;

class Test<T>
{
    T _value;

    public Test(T t)
    {
    // The field has the same type as the parameter.
        this._value = t;
    }

    public void Write()
    {
        Console.WriteLine(this._value);
    }
}

class Program
{
    static void Main()
    {
    // Use the generic type Test with an int type parameter.
    Test<int> test1 = new Test<int>(5);
    // Call the Write method.
    test1.Write();

    // Use the generic type Test with a string type parameter.
    Test<string> test2 = new Test<string>("cat");
    test2.Write();
    }
}

And you can set a constraints in generic class. 您可以在通用类中设置constraints

For example 例如

using System;
using System.Data;

/// <summary>
/// Requires type parameter that implements interface IEnumerable.
/// </summary>
class Ruby<T> where T : IDisposable
{
}

/// <summary>
/// Requires type parameter that is a struct.
/// </summary>
class Python<T> where T : struct
{
}

/// <summary>
/// Requires type parameter that is a reference type with a constructor.
/// </summary>
class Perl<V> where V : class, new()
{
}

class Program
{
    static void Main()
    {
        // DataTable implements IDisposable so it can be used with Ruby.
        Ruby<DataTable> ruby = new Ruby<DataTable>();

    // Int is a struct (ValueType) so it can be used with Python.
    Python<int> python = new Python<int>();

    // Program is a class with a parameterless constructor (implicit)
    // ... so it can be used with Perl.
    Perl<Program> perl = new Perl<Program>();
    }
}

And for generic method 而对于通用方法

using System;
using System.Collections.Generic;

class Program
{
    static List<T> GetInitializedList<T>(T value, int count)
        {
        // This generic method returns a List with ten elements initialized.
        // ... It uses a type parameter.
        // ... It uses the "open type" T.
        List<T> list = new List<T>();
        for (int i = 0; i < count; i++)
        {
            list.Add(value);
        }
        return list;
        }

    static void Main()
        {
        // Use the generic method.
        // ... Specifying the type parameter is optional here.
        // ... Then print the results.
        List<bool> list1 = GetInitializedList(true, 5);
        List<string> list2 = GetInitializedList<string>("Perls", 3);
        foreach (bool value in list1)
        {
            Console.WriteLine(value);
        }
        foreach (string value in list2)
        {
            Console.WriteLine(value);
        }
        }
    }

Resource Of my answer are these link. 资源我的答案是这些链接。 C# Generic Class Generic Method C#泛型类 泛型方法

Yes you can but you have to 'inform' the other class which type you are working with, like that: 是的,可以,但是您必须“通知”正在使用的其他类型,例如:

public class StackType<t>
{
    public void Generate()
    {
    }
}

public class MyClass<T>
{
    public MyClass(StackType<T> stack)
    {
        stack.Generate();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM