zoukankan      html  css  js  c++  java
  • 【转】C#泛型经典示例(转载)

    泛型是一种特殊的类型,它把指定类型的工作推迟到客户端代码声明并实例化类或方法的时候进行。
    下面是两个经典示例:
    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(123456);
                
    double dMax = Max<double>(1.234.56);//可以指定返回类型
                
    //
                int iConvert = Convert<int>("123456");
                
    float fConvert = Convert<float>("123.456");
                
    //
                System.Windows.Forms.MessageBox.Show(iMax + "|" + dMax + "|" + iConvert + "|" + fConvert);
            }
        }
    }
    from:http://www.it100.info/csharp-generic.html
  • 相关阅读:
    hdu4059 The Boss on Mars
    cf475D CGCDSSQ
    HDU
    cf1447D Catching Cheaters
    cf1440 Greedy Shopping
    Treats for the Cows
    dp废物学会了记录路径
    D. Jzzhu and Cities
    cf1359D Yet Another Yet Another Task
    关于sg函数打表的理解
  • 原文地址:https://www.cnblogs.com/lzh_527/p/2325545.html
Copyright © 2011-2022 走看看