泛型是一种特殊的类型,它把指定类型的工作推迟到客户端代码声明并实例化类或方法的时候进行。
下面是两个经典示例:
from:
http://www.it100.info/csharp-generic.html
下面是两个经典示例:
1.输入一个字符串,转化为想要的类型。
利用泛型的特性,返回值可以是指定的类型。
2.比较两个对象,返回值较大的一个。
using
System;
using System.Collections.Generic;
using System.Text;
namespace FamilyManage
{
class CGeneric
{
// 数据转换
static public T Convert < T > ( string s) where T : IConvertible
{
return (T)System.Convert.ChangeType(s, typeof (T));
}
// 取两个数较大的一个
static public T Max < T > (T first, T second) where T : IComparable < T >
{
if (first.CompareTo(second) > 0 )
return first;
return second;
}
// 使用
static public void test()
{
//
int iMax = Max( 123 , 456 );
double dMax = Max < double > ( 1.23 , 4.56 ); // 可以指定返回类型
//
int iConvert = Convert < int > ( " 123456 " );
float fConvert = Convert < float > ( " 123.456 " );
//
System.Windows.Forms.MessageBox.Show(iMax + " | " + dMax + " | " + iConvert + " | " + fConvert);
}
}
}
using System.Collections.Generic;
using System.Text;
namespace FamilyManage
{
class CGeneric
{
// 数据转换
static public T Convert < T > ( string s) where T : IConvertible
{
return (T)System.Convert.ChangeType(s, typeof (T));
}
// 取两个数较大的一个
static public T Max < T > (T first, T second) where T : IComparable < T >
{
if (first.CompareTo(second) > 0 )
return first;
return second;
}
// 使用
static public void test()
{
//
int iMax = Max( 123 , 456 );
double dMax = Max < double > ( 1.23 , 4.56 ); // 可以指定返回类型
//
int iConvert = Convert < int > ( " 123456 " );
float fConvert = Convert < float > ( " 123.456 " );
//
System.Windows.Forms.MessageBox.Show(iMax + " | " + dMax + " | " + iConvert + " | " + fConvert);
}
}
}