对c#中范型的理解
object中可以存放任何类型,需要的时候经过强制转换取出来,因为需要装箱和拆箱的操作,所以性能不高,而且在强制转换时还容易出错。而范型是运行时才确定实际类型,所以能避免上述不足...
定义一个范型类型TypeList
class TypeList<MyType> //范型类型
{
MyType m_value; //范型类型的变量
public MyType GetSetValue
{
get
{
return m_value;
}
set
{
m_value = value;
}
}
}
使用上面定义的范型类型
class TimeSpanPropertiesDemo
{
static void Main()
{
//声明对象为TypeList型,TypeList中定义的范型类型为int型
TypeList<int> MyList = new TypeList<int>();
MyList.GetSetValue = 23;
int test = MyList.GetSetValue;
//声明对象为TypeList型,TypeList中定义的范型类型为string型
TypeList<string> MyList2 = new TypeList<string>();
MyList2.GetSetValue = “Hello”;
string test2 = MyList2.GetSetValue;
}
}
由上可知,我们将范型的类型(MyType)做为了“变量”,分别传递了int、string...