2013-10-01 4 views
1

Я типа, используя дженерики как этотC#, как использовать общий тип

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

В другом классе, я хотел бы написать метод, который принимает этот стек типа для любого T:

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

Возможно ли это?

ответ

8

Сделайте либо класс, либо метод в MyClass generic.

Общий класс:

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

Общий метод:

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

Который подходит зависит от сферы, в которой вы хотите, чтобы T быть переменным. Если один экземпляр MyClass должен иметь возможность вызывать MyMethod с несколькими типами стеков, тогда метод должен быть общим. Если один экземпляр MyClass должен потребовать все вызовы MyMethod для передачи того же типа стека, то весь класс должен быть общим.

6

Либо:

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

или

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

правильно.

0

Да вы можете, но вы должны «сообщить» другой класс, какой тип вы работаете, как это:

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

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

Есть два типа родовое:

один = общий метод

два = общий класс

Например:

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

И вы можете установить constraints в универсальном классе.

Например

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

И для универсального метода

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

Ресурс моего ответа являются эти связи. C# Generic ClassGeneric Method

Смежные вопросы