【发布时间】:2013-06-04 14:22:04
【问题描述】:
最近我遇到了下面的代码。
public interface IBlog<T>
{
void Add(T blog);
IEnumerable<T> GetAll();
T GetRecord(int id);
void Delete(int id);
}
这里的T 是什么?使用它的目的是什么?
【问题讨论】:
最近我遇到了下面的代码。
public interface IBlog<T>
{
void Add(T blog);
IEnumerable<T> GetAll();
T GetRecord(int id);
void Delete(int id);
}
这里的T 是什么?使用它的目的是什么?
【问题讨论】:
一个简单的例子,你可以有一个方法
T GetDefault<T>()
{
return default(T);
}
然后打电话
int zero = GetDefault<int>();
方法中的T 将是int 的类型。
在c# 中有List<int> 或List<string>,例如,这是在using generics, read more... 中实现的
【讨论】:
您想知道的是Generics。泛型提供了一种很好的动态处理方式。您可能已经知道也可能不知道,但List 和Dictionary 使用泛型。
List<Foo> foos = new List<Foo>(); //Means everything within that list will be of Foo type
List<Bar> bars= new List<Bar>(); //Again, means everything within that list will be of Bar type
【讨论】: