粘些MSDN中的介绍:泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。泛型将类型参数的概念引入 .NET Framework,类型参数使得设计如下类和方法成为可能:这些类和方法将一个或多个类型的指定推迟到客户端代码声明并实例化该类或方法的时候。例如,通过使用泛型类型参数 T,您可以编写其他客户端代码能够使用的单个类,而不致引入运行时强制转换或装箱操作的成本或风险,如下所示: // Declare the generic class public class GenericList<T> { void Add(T input) { } } class TestGenericList { private class ExampleClass { } static void Main() { // Declare a list of type int GenericList<int> list1 = new GenericList<int>(); // Declare a list of type string GenericList<string> list2 = new GenericList<string>(); // Declare a list of type ExampleClass GenericList<ExampleClass> list3 = new GenericList<ExampleClass>(); } }
/// <summary> /// /// </summary> /// <param name="TableName"></param> /// <param name="sql"></param> /// <returns></returns> private T GetTableModel<T>(string TableName,IDataReader dr) { try { //IDataReader dr = OracleHelper.GetDataReader(sql); Assembly ass = Assembly.Load("Baoxuan.Model"); Type t = ass.GetType("Baoxuan.Model."+TableName.ToUpper()); T model = (T)Activator.CreateInstance(t); if(dr.Read()) { for(int i=0;i<dr.FieldCount;i++) { PropertyInfo pi = model.GetType().GetProperty(dr.GetName(i));
// Declare the generic class
public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int
GenericList<int> list1 = new GenericList<int>(); // Declare a list of type string
GenericList<string> list2 = new GenericList<string>(); // Declare a list of type ExampleClass
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}
///
/// </summary>
/// <param name="TableName"></param>
/// <param name="sql"></param>
/// <returns></returns>
private T GetTableModel<T>(string TableName,IDataReader dr)
{
try
{
//IDataReader dr = OracleHelper.GetDataReader(sql);
Assembly ass = Assembly.Load("Baoxuan.Model");
Type t = ass.GetType("Baoxuan.Model."+TableName.ToUpper());
T model = (T)Activator.CreateInstance(t);
if(dr.Read())
{
for(int i=0;i<dr.FieldCount;i++)
{
PropertyInfo pi = model.GetType().GetProperty(dr.GetName(i));
switch(pi.PropertyType.ToString())
{
case"System.Double":
pi.SetValue(model,CheckData.ToDouble(dr[i]),null);
break;
case"System.String":
pi.SetValue(model,CheckData.ToString(dr[i]),null);
break;
}
}
}
return model;
}
catch(Exception exp)
{
throw new Exception(exp.ToString());
}
}
using System;class Test
{
static void Main()
{
Console.WriteLine(Max(1)); // 输出: 1
Console.WriteLine(Max(.3, -.5)); // 输出: 0.3
Console.WriteLine(Max(0M, -3M, 3.14M)); // 输出: 3.14
Console.WriteLine(Max(9f, -1f, 3.14f, -2.718f)); // 输出: 9
Console.WriteLine(Max(0u, 23u, 3114u, 120718u, 5678u)); // 输出: 120718
} static T? Max<T>(params T[] x)
where T: struct, IComparable
{
if (x.Length == 0) return null;
T a = x[0];
foreach (T i in x)
if (a.CompareTo(i) < 0) a = i;
return a;
}
}
在定义时用<T>代替类型,在实例化时(使用时)确定类型,如<int>