C# 泛型类、泛型方法、泛型委托和扩展方法

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var dogCage = new Cage<Dog>(1);
            // 放进去
            dogCage.Putin(new Dog("jack"));
            dogCage.Putin(new Dog("job"));
            // 取出来
            var dog2= dogCage.Takeout();
            dog2.ShowName();
        }
    }
    public class Dog
    {
        private string Name;
        private int age = 0;
        public Dog(string dname)
        {
            Name = dname;
        }
        public void ShowName()
        {
            Console.WriteLine("这是一条狗:{0}", Name);
        }
        public void ShowAge()
        {
            Console.WriteLine("宠物的年龄为" + age);
        }
        // 使用重载运算符
        public static Dog operator ++(Dog dog)
        {
            dog.age++;  // 年龄自增
            return dog;
        }
    }
    // 泛型类的使用,定义笼子
    public class Cage<T>
    {
        T[] array;  // 定义一个数组
        readonly int Size;  // 定义一个笼子大小
        int num;  // 定义现有的数量
        public Cage(int n)
        {
            // 构造函数
            Size = n;
            num = 0;
            array = new T[Size];  // 设置数组(笼子)的大小
        }
        // 将宠物放到笼子里
        public void Putin(T pet)
        {
            // 如果还没有满,将宠物放到笼子里
            if (Size > num)
                array[num++] = pet;
            else
                Console.WriteLine("宠物已经装满了...");
        }
        // 将宠物取出来
        public T Takeout()
        {
            // 如果有宠物,那么取出来
            if (num > 0)
                return array[--num];
            else
            {
                // 如果没有宠物了,那么返回空
                Console.WriteLine("笼子空了!!!");
                return default(T);
            }
        }
    }
}

 泛型方法:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 使用泛型方法
            var dog1 = new Dog("jack");
            dog1.isHabby<Person>(new Person());
            dog1.isHabby<int>(3);
        }
    }
    public class Dog
    {
        private string Name;
        private int age = 0;
        public Dog(string dname)
        {
            Name = dname;
        }
        public void ShowName()
        {
            Console.WriteLine("这是一条狗:{0}", Name);
        }
        public void ShowAge()
        {
            Console.WriteLine("宠物的年龄为" + age);
        }
        // 泛型方法
        public void isHabby<T>(T target)
        {
            Console.WriteLine("看到 {0} 很开心!!!", target.ToString());
        }
    }
    public class Person
    {
        //
    }
}

使用where添加约束:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var dog = new Dog("jack");
            dog.isHabby<Person>(new Person());
            // 下面方法会失败,因为使用where添加了约束
            //dog.isHabby<int>(3);
        }
    }
    public class Dog
    {
        private string Name;
        public Dog(string name)
        {
            Name = name;
        }
        public void ShowName()
        {
            Console.WriteLine("宠物的名字是:" + Name);
        }
        // where T:class 表示对该方法添加了只能够传递类的约束
        public void isHabby<T>(T target) where T:class
        {
            Console.WriteLine("见到{0}很高兴...", target.ToString());
        }
    }
    public class Person
    {
        //
    }
}

使用where 还能够对特定的类进行约束:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var dog = new Dog("jack");
            dog.isHabby<Cat>(new Cat());
        }
    }
    public class Aminal
    {
        //
    }
    public class Cat : Aminal
    {
        //
    }
    public class Dog
    {
        private string Name;
        public Dog(string name)
        {
            Name = name;
        }
        public void ShowName()
        {
            Console.WriteLine("宠物的名字是:" + Name);
        }
        public void isHabby<T>(T target) where T:Aminal
        {
            Console.WriteLine("见到{0}很高兴...", target.ToString());
        }
    }
}

泛型接口:允许我们将接口成员的参数和返回值类型设置为泛型参数的接口。

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Labardor dog1 = new Labardor();
            dog1.Act(new SiteDog());
        }
    }
    public abstract class DogCmd
    {
        // 定义抽象方法
        public abstract string GetCmd();
    }
    public class SiteDog : DogCmd
    {
        // 重写抽象方法
        public override string GetCmd()
        {
            return "site";
        }
    }
    // 泛型接口
    public interface IDogLearn<C> where C : DogCmd
    {
        // 接口函数
        void Act(C cmd);
    }
    public class Labardor : IDogLearn<SiteDog>
    {
        // 实现接口函数
        public void Act(SiteDog cmd)
        {
            Console.WriteLine(cmd.GetCmd());
        }
    }
}

////////////////////////////////////////////////////////

另一个例子

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

namespace ConsoleApplication2
{
    class Program
    {
        class Employee
        {
            protected string id;
            protected string name;
            protected string age;
            // 无参构造函数
            public Employee() { }
            // 有参构造函数
            public Employee(string uid, string uname, string uage)
            {
                this.id = uid;
                this.name = uname;
                this.age = uage;
            }
            // 使用泛型
            public void printMessage(Stack<Employee> emcee)
            {
                foreach(Employee s in emcee)
                {
                    Console.WriteLine("id:{0}, name:{1}, age:{2}", s.id, s.name, s.age);
                }
            }
        }
        static void Main(string[] args)
        {
            // 调用泛型
            Stack<Employee> empl = new Stack<Employee>();
            do
            {
                Console.Write("请输入一个id:");
                string id = Console.ReadLine();
                Console.Write("请输入一个name:");
                string name = Console.ReadLine();
                Console.Write("请输入一个age:");
                string age = Console.ReadLine();
                Employee e = new Employee(id, name, age);
                empl.Push(e);
                Console.Write("是否继续(Y/N):");
            } while (Console.ReadLine().ToUpper() == "Y");
            Employee a = new Employee();
            a.printMessage(empl);
        }
    }
}

 使用泛型相比于集合的好处:

1.在编译时就会报错,不需要等到编译时才报错。

2.泛型避免了集合中add添加时类型不一样的装箱和拆箱。

3.代码重用行更高。

泛型已经能够满足很多需求,但是如果要在性能上有提升可以了解一下System.Collections.Specialized

泛型委托

Func<...,out >:有返回值的泛型委托,最后一个为返回值。

Action<...>:无返回值的泛型委托。

扩展方法

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

namespace 社区学习
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 把集合中小于8的字符串打印出来
            // 定义一个集合
            List<string> strList = new List<string>()
            {
                "2","9","48","85","25"
            };
            IEnumerable<string> Temps = strList.Where(delegate (string a) { return a.CompareTo("8") < 0; });  // 筛选,注是字符串小于8而不是字符串数值
            foreach(string temp in Temps)
            {
                Console.WriteLine(temp);
            }
            #endregion
            Console.WriteLine("================================");
            #region 使用扩展方法
            IEnumerable<string> Items = strList.MyWhere(delegate (string a) { return a.CompareTo("8") < 0; });
            foreach (string Item in Items)
            {
                Console.WriteLine(Item);
            }
            #endregion
        }
    }

    // 定义扩展方法
    public static class MyListExt
    {
        public static List<string> MyWhere(this List<string> list, Func<string, bool> funcWhere)
        {
            List<string> result = new List<string>();
            foreach(string item in list)
            {
                if(funcWhere(item))
                {
                    result.Add(item);
                }
            }
            return result;
        }
    }
}
原文地址:https://www.cnblogs.com/namejr/p/10269663.html