using
System;
// 我们在编写程序时,经常遇到两个模块的功能非常相似,只是一个是处理int数据,另一个是处理string数据,或者其他自定义的数据类型,但我们没有办法,只能分别写多个方法处理每个数据类型,因为方法的参数类型不同。有没有一种办法,在方法中传入通用的数据类型,这样不就可以合并代码了吗?泛型的出现就是专门解决这个问题的。
namespace Generic
{
class Program
{
static void Main( string [] args)
{
// 一个普通的类,只能传入int类型的参数。
print p = new print( 5 );
// 使用了泛型,只需要在 < > 中定义参数类型就可以了。
print1 < int > p1 = new print1 < int > ( 5 );
print1 < string > p2 = new print1 < string > ( " p2 " );
// 泛型参数的约束,第一个必须是值类型(struct),第二个是引用类型(class)。
print2 < int , string > p3 = new print2 < int , string > ( 5 , " p3 " );
// 泛型方法,可以对方法传入不同类型的参数。
print3 p4 = new print3();
p4.print( " aaa " , " bbb " , " ccc " );
p4.print( 111 , 222 , 333 );
Console.ReadLine();
// 输出结果
// 5
// 5
// p2
// 5 p3
// aaa
// bbb
// ccc
// 111
// 222
// 333
}
}
class print
{
public print( int i)
{
Console.WriteLine(i);
}
}
class print1 < T >
{
public print1(T t)
{
Console.WriteLine(t);
}
}
// 泛型约束,使用了where关键字。
class print2 < T, V > where T: struct where V: class
{
public print2(T t,V v)
{
Console.WriteLine(t + " " + v);
}
}
class print3
{
public print3(){}
public void print < T > ( params T[] p)
{
foreach (T t in p)
{
Console.WriteLine(t);
}
}
}
}
// 我们在编写程序时,经常遇到两个模块的功能非常相似,只是一个是处理int数据,另一个是处理string数据,或者其他自定义的数据类型,但我们没有办法,只能分别写多个方法处理每个数据类型,因为方法的参数类型不同。有没有一种办法,在方法中传入通用的数据类型,这样不就可以合并代码了吗?泛型的出现就是专门解决这个问题的。
namespace Generic
{
class Program
{
static void Main( string [] args)
{
// 一个普通的类,只能传入int类型的参数。
print p = new print( 5 );
// 使用了泛型,只需要在 < > 中定义参数类型就可以了。
print1 < int > p1 = new print1 < int > ( 5 );
print1 < string > p2 = new print1 < string > ( " p2 " );
// 泛型参数的约束,第一个必须是值类型(struct),第二个是引用类型(class)。
print2 < int , string > p3 = new print2 < int , string > ( 5 , " p3 " );
// 泛型方法,可以对方法传入不同类型的参数。
print3 p4 = new print3();
p4.print( " aaa " , " bbb " , " ccc " );
p4.print( 111 , 222 , 333 );
Console.ReadLine();
// 输出结果
// 5
// 5
// p2
// 5 p3
// aaa
// bbb
// ccc
// 111
// 222
// 333
}
}
class print
{
public print( int i)
{
Console.WriteLine(i);
}
}
class print1 < T >
{
public print1(T t)
{
Console.WriteLine(t);
}
}
// 泛型约束,使用了where关键字。
class print2 < T, V > where T: struct where V: class
{
public print2(T t,V v)
{
Console.WriteLine(t + " " + v);
}
}
class print3
{
public print3(){}
public void print < T > ( params T[] p)
{
foreach (T t in p)
{
Console.WriteLine(t);
}
}
}
}