C#-泛型

发布于:2025-03-03 ⋅ 阅读:(90) ⋅ 点赞:(0)

List<T>

集合赋值,不能直接new_list = old_list,都是指向同一个地址

List<string> old_list = new List<string>();
List<string> new_list = new List<string>(old_list);

 集合、数组转换,ToList()、ToArray()   

list.AddRange(array);将数组直接添加到集合

list.RemoveAt(2);按照索引删除

Dictionary<K,V>

初始化,通过key获得对象,遍历key,遍历value

Dictionary<string, Student> s = new Dictionary<string, Student>
{
    ["first"] = new Student("tom", 1),
    ["second"] = new Student("jack", 2)
};

Console.WriteLine(s["first"]);//输出的是对象
Console.WriteLine(s["first"].name);

foreach (string item in s.Keys)
    Console.Write(item + " ");

Console.WriteLine();

foreach (Student item in s.Values)
    Console.Write(item.ToString() + " ");

泛型方法/类

namespace test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(add<int, int, int>(1,2));

            MyList<string> stringList = new MyList<string>();
            stringList.Add("string1");
            stringList.AddRange(new string[] { "string2", "string3" });
            stringList[1] = "aaa";
            Console.WriteLine(stringList.Length + stringList[1]);
        }
        static T add<T, T1, T2>(T1 a,T2 b) where T:struct, T1, T2
        {
            dynamic num1 = a;
            dynamic num2 = b;
            return num1 + num2;
        }
    }
    class MyList<T>
    {
        private List<T> list = new List<T>();
        //索引器
        public T this[int index]
        {
            get { return list[index]; }
            set { list[index] = value; }
        }
        public int Length
        {
            get { return list.Count; }
        }
        public void AddRange(T[] item)
        {
            list.AddRange(item);
        }
        public void Add(T item)
        {
            list.Add(item);
        }
    }
}

default

会自动根据引用类型或值类型赋默认值

class Program
{
    static void Main(string[] args)
    {
        MyClass<int, string> m = new MyClass<int, string>();
    }
    
}
class MyClass<T1, T2>
{
    private T1 data1;
    private T2 data2;
    public MyClass()
    {
        data1 = default(T1);
        data2 = default(T2);
    }
}

约束和动态类型dynamic

class MyClass<T1, T2, T3>
    where T1 : struct //值类型
    where T2 : class  //引用类型
    where T3 : new() //表示T3类中必须有一个无参构造方法
{
    public List<T2> CourseList { get; set; }
    public T3 Publisher { get; set; }
    public MyClass()
    {
        this.CourseList = new List<T2>();
        this.Publisher = new T3();//如果没有where T3 : new() 会报错
    }
    public T2 BuyCourse(T1 index)
    {
        dynamic _index = index;
        return this.CourseList[_index];
    }
}


网站公告

今日签到

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