C#泛型内部原理
2012-09-29 08:25
239 查看
泛型相当于C++的模板
泛型方法
static
void Fly<T,K>(T i,K t)
{
}
泛型委托
delegate
void MyDelegate<T1,T2>(T1 t1,T2 t2);
.net中的func<>泛型
EventHandler 委托事件
泛型约束
• 约束父类或者接口:AAA<T> where T:IDbConnection
class
Personlist<T>where T :
Person
{
public
void Doit(T p)
{
//p.Name因为约定了T必须是继承自Person,所以可以类的
//内部调用
}
}
class
Person
{
public
string Name { get;
set; }
}
class
Chinese:Person
{
public
string Hukou { get;
set; }
}
•
• 约束构造函数:AAA <T> where T:new(), AAA<T> where T:new()。
• 泛型创建一个返回N个对象的方法。
• 泛型创建一个对任意数据进行取最大元素的方法
如:
这能够约束泛型的类型:对泛型委托和泛型类都一样的
static
List<T>CreateList<T>(int n)
where T : new()//只能是无参数的构造函数
{
List<T>List=new
List<T>();
for(int i = 0; i < n; i++)
{
T p = newT();
List.Add(p);
}
returnList;
}
Int?其实就是泛型的类型NUllable(通过reflector 反编译)
Lazy<>懒做的对象,作用是当用到这对象时才创建对象
Lazy<Person> person =
newLazy<Person>();
Fly<string,int>("aa",3);
stringss= person.Value.Name;
//lazy的value用来延迟创建对象,以减少内存
自己写一个Lazy
class
MyLazy<T>where T :
new()
{
privateT instance;
publicT value
{
get{
if(instance==null)
{
instance = newT();
}
returninstance;
}
}
}
字段是对象被new出来了以后
Default(T)
泛型方法
static
void Fly<T,K>(T i,K t)
{
}
泛型委托
delegate
void MyDelegate<T1,T2>(T1 t1,T2 t2);
.net中的func<>泛型
EventHandler 委托事件
泛型约束
• 约束父类或者接口:AAA<T> where T:IDbConnection
class
Personlist<T>where T :
Person
{
public
void Doit(T p)
{
//p.Name因为约定了T必须是继承自Person,所以可以类的
//内部调用
}
}
class
Person
{
public
string Name { get;
set; }
}
class
Chinese:Person
{
public
string Hukou { get;
set; }
}
•
• 约束构造函数:AAA <T> where T:new(), AAA<T> where T:new()。
• 泛型创建一个返回N个对象的方法。
• 泛型创建一个对任意数据进行取最大元素的方法
如:
这能够约束泛型的类型:对泛型委托和泛型类都一样的
static
List<T>CreateList<T>(int n)
where T : new()//只能是无参数的构造函数
{
List<T>List=new
List<T>();
for(int i = 0; i < n; i++)
{
T p = newT();
List.Add(p);
}
returnList;
}
Int?其实就是泛型的类型NUllable(通过reflector 反编译)
Lazy<>懒做的对象,作用是当用到这对象时才创建对象
Lazy<Person> person =
newLazy<Person>();
Fly<string,int>("aa",3);
stringss= person.Value.Name;
//lazy的value用来延迟创建对象,以减少内存
自己写一个Lazy
class
MyLazy<T>where T :
new()
{
privateT instance;
publicT value
{
get{
if(instance==null)
{
instance = newT();
}
returninstance;
}
}
}
字段是对象被new出来了以后
Default(T)
相关文章推荐
- 泛型的内部原理
- 【8】Java泛型:泛型内部原理--泛型擦除
- 泛型的内部原理:类型擦除以及类型擦除带来的问题
- 泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型 8 泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- 泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型 泛型的内部原理
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- 泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- 泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- java泛型(二)、泛型的内部原理:类型擦除以及类型擦除带来的问题
- 泛型的内部原理:类型擦除以及类型擦除带来的问题