Книга: C# 2008 Programmer

Generic Methods

Generic Methods

In addition to generic classes and interfaces, you can also define generic methods. Consider the following class definition and the method contained within it:

public class SomeClass {
 public void DoSomething<T>(T t) {}
}

Here, DoSomething() is a generic method. To use a generic method, you need to provide the type when calling it:

SomeClass sc = new SomeClass();
sc.DoSomething<int>(3);

The C# compiler, however, is smart enough to deduce the type based on the argument passed into the method, so the following statement automatically infers T to be of type String:

sc.DoSomething("This is a string"); //---T is String---

This feature is known as generic type inference.

You can also define a constraint for the generic type in a method, like this:

public class SomeClass {
 public void DoSomething<T>(T t) where T : IComparable<T> {
 }
}

If you need the generic type to be applicable to the entire class, define the type T at the class level:

public class SomeClass<T> where T : IComparable<T> {

 public void DoSomething(T t) { }

}

In this case, you specify the type during the instantiation of SomeClass:

SomeClass<int> sc = new SomeClass<int>();
sc.DoSomething(3);

You can also use generics on static methods, in addition to instance methods as just described. For example, the earlier DoSomething() method can be modified to become a static method:

public class SomeClass {
 public static void DoSomething<T>(T t)
  where T : IComparable<T> {}
}

To call this static generic method, you can either explicitly specify the type or use generic type inference:

SomeClass.DoSomething(3);
//---or---
SomeClass.DoSomething<int>(3);

Оглавление книги


Генерация: 0.704. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз