c#基础(13.泛型)

发布于:2022-08-09 ⋅ 阅读:(359) ⋅ 点赞:(0)

泛型允许根据不同的类型参数设计类,方法,接口,委托。

泛型的作是代码可重用性,类型安全性。

泛型集合类是C#常见的内置类型。

using System;
using System.Collections.Generic;

namespace _13.泛型
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var t = new Test<int>();
            t.Value = 10;

            var t2 = new Test<string>();
            t2.Value = "abc";

            Test(new List<int>() { 1 });

            Test(new List<string>() { "abc","efg" });

            Test(new List<MyTest>() { new MyTest(), new MyTest()});

            Test1<int> test1 = (arg) => { Console.WriteLine(arg); };
        }

        //这个是一个简单的泛型方法
        static void Test<T>(IList<T> args)
        {
            foreach (T arg in args)
            {
                Console.Write(arg);
                Console.Write(",");
            }
            Console.WriteLine();
        }
    }

    public class MyTest
    { 
    
    }

    //这是一个简单的泛型类,最大的特点就是可重用性和类型安全性
    public class Test<T>
    { 
        public T Value { get; set; }
    }

    //泛型委托
    public delegate void Test1<T>(T arg);

    //泛型接口
    public interface A<T>
    {
        public T Get(T arg);
    }

    //继承一个泛型接口
    public class AA : A<int>
    {
        public int Get(int arg)
        {
            return arg + 10;
        }
    }
}
 

13.泛型

 


 


网站公告

今日签到

点亮在社区的每一天
去签到