1.预定义
编译器为VS2013 编译环境为Framework 4.0 项目类型为控制台应用程序
预定义实体类
class TestClass
{
int _Key = 0;
public int Key
{
get { return _Key; }
set { _Key = value; }
}
String _Value = String.Empty;
public String Value
{
get { return _Value; }
set { _Value = value; }
}
}
2.泛型参数
函数定义
public static void TestFunc1<T>(T a)
{
var testclass = a as TestClass;
Console.WriteLine("key:{0}\tvalue:{1}",testclass.Key,testclass.Value);
}
调用
static void Main(string[] args)
{
TestClass testclass = new TestClass();
testclass.Key = 1;
testclass.Value = "testclass";
TestFunc1<TestClass>(testclass);
Console.ReadLine();
}
运行结果
3.泛型返回值
函数定义
public static T TestFunc2<T>(int key,String value)
{
TestClass testclass = new TestClass();
testclass.Key = key;
testclass.Value = value;
return (T)(object)testclass;
}
调用
static void Main(string[] args)
{
var a = TestFunc2<TestClass>(1,"testclass");
TestFunc1<TestClass>(a);
Console.ReadLine();
}
运行结果与1相同