其实C#模版的能力不强,一些代码便可以基本展示C#模版的能力。并且C#的模版就在也没有更多的能力了。最初接触C# 2.0的模版时,感到兴奋,没多少天就觉得其能力还是很受限的。可能这也体现了简单易用的一个原则吧,毕竟C#是一个大众化的语言!
//不同于C++,需要使用template<class T, class V>
//或者template<typename T, typename V>声明模板参数
public class A<T, V>
{
public static int I = 0;
}
//部分实例化
public class A<T> : A<T, object>
{
public static new int I = A<T, object>.I + 1;
}
//部分实例化,约束T必须实现接口ICollection<T>
public class C<T> : A<T, string> where T : ICollection<T>
{
}
public class D
{
//模板化的方法,约束T必须有缺省构造函数
public T F<T>() where T : new()
{
return new T();
}
}
//或者template<typename T, typename V>声明模板参数
public class A<T, V>
{
public static int I = 0;
}
//部分实例化
public class A<T> : A<T, object>
{
public static new int I = A<T, object>.I + 1;
}
//部分实例化,约束T必须实现接口ICollection<T>
public class C<T> : A<T, string> where T : ICollection<T>
{
}
public class D
{
//模板化的方法,约束T必须有缺省构造函数
public T F<T>() where T : new()
{
return new T();
}
}