C# 泛型使用

来源:互联网 发布:s7 200编程电缆 编辑:程序博客网 时间:2024/06/05 06:10

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相同