C# 三十六、泛型

概念:

  • 所谓泛型,即通过参数化类型来实现在同一份代码上操作多种数据类型。
  • 泛型编程是一种编程范式,它利用“参数化类型”将类型抽象化,从而实现更为灵活的复用。
  • 使用泛型时,参数化的类型可以设置多个,以逗号隔开。

泛型方法

代码示例:

    class Program
    {
        static void Main(string[] args)
        {
            Function<int>(1);
            Function<string>("a");
            Function<char>('.');

            Console.ReadKey();
        }

        static void Function<T>(T t)
        {
            if (t.GetType()==typeof(int))
            {
                Console.WriteLine("123");
            }
            else if (t.GetType() == typeof(string))
            {
                Console.WriteLine("abc");
            }
            else
            {
                Console.WriteLine("……");
            }

        }
    }

--->
123
abc
……

泛型类

代码示例:

    class Program
    {
        static void Main(string[] args)
        {
            FX<int> fX1 = new FX<int>();
            fX1.Function(1);

            FX<string> fX2 = new FX<string>();
            fX2.Function("a");

            FX<char> fX3 = new FX<char>();
            fX3.Function('.');

            Console.ReadKey();
        }        
    }

    class FX<T>
    {
        public void Function(T t)
        {
            if (t.GetType() == typeof(int))
            {
                Console.WriteLine("123");
            }
            else if (t.GetType() == typeof(string))
            {
                Console.WriteLine("abc");
            }
            else
            {
                Console.WriteLine("……");
            }
        }
    }

--->
123
abc
……

泛型接口

代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace fanxingjiekou
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.add(10);
            student s = new student();
            s.add("你好");


            Console.ReadKey();
        }
        

    }
    interface Ipe<T>
    {
        void add(T t);
    }

    class Person : Ipe<int>
    {
        public void add(int a)
        {
            Console.WriteLine(a);
        }
    }

    class student : Ipe<string>
    {
        public void add(string name)
        {
            Console.WriteLine(name);
        }
    }
}

--->
10
你好

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值