泛型(CSDN转载)

函数的参数不同叫多态,函数的参数类型可以不确定吗?

函数的返回值只能是一个吗?函数的返回值可以不确定吗?

泛型是一种特殊的类型,它把指定类型的工作推迟到客户端代码声明并实例化类或方法的时候进行。

下面是两个经典示例:

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);

        }

    }

}

  System.Convert.ChangeType(s, typeof(T));这个函数,在以往的项目中用的比较少,用的最多的还是Convert.ToInt()和Convert.ToDouble()。一般多是把一个字符串转化需要的整型数据或者浮点型数据。例如:

  

            string intString="123";
            int result=System.Convert.ToInt32(intString);
            Console.WriteLine(result); //输出123  

  也有用Int类或者Double类的Parse或者TryParse函数进行转化的,在此不在举例。把注意力拉回到System.Convert.ChangeType(s, typeof(T));这个函数。

  ChangeType:返回一个指定类型的对象,该对象的值等效于指定的对象。此方法有四种函数重载。如下面的表格所示:

        double d = -2.345;
        int i = (int)Convert.ChangeType(d, typeof(int));

        Console.WriteLine("The double value {0} when converted to an int becomes {1}", d, i);

        string s = "12/12/98";
        DateTime dt = (DateTime)Convert.ChangeType(s, typeof(DateTime));

        Console.WriteLine("The string value {0} when converted to a Date becomes {1}", s, dt);     

  

                                          想要了解更多请参看MSDN的Convert类。

原文地址:https://www.cnblogs.com/zhangyuanbo12358/p/3612069.html