c#学习笔记-------------索引器,列表和泛型

学习笔记 / 2023-08-08 / 原文

一、索引器

参考文章:https://www.cainiaojc.com/csharp/csharp-indexer.html

索引器类似于属性。 很多时候,创建索引器与创建属性所使用的编程语言特性是一样的。

索引器使属性可以被索引:使用一个或多个参数引用的属性。 这些参数为某些值集合提供索引。

索引器语法

可以通过变量名和方括号访问索引器。 将索引器参数放在方括号内:

var item = someObject["key"];
someObject["AnotherKey"] = item;
using System;
using System.Collections.Generic;
using System.Text;

namespace _14_索引器
{
    class Test
    {

        private string[] name = new string[10];

        public string this[int index]
        {
            get
            {
                return name[index];
            }
            set
            {
                name[index] = value;
            }
        }

    }
}
  Test t = new Test();
            t[0] = "张三";
            Console.WriteLine(t[9]);

 

二、列表

参考文章:https://www.cainiaojc.com/csharp/csharp-list.html

List <T>是强类型对象的集合,可以通过索引对其进行访问,

并具有用于排序,搜索和修改列表的方法。

它是System.Collection.Generic命名空间下的ArrayList的泛型版本。

List <T>特性

  • List<T> 等效于ArrayList,它实现了IList <T>。

  • 它在System.Collection.Generic命名空间下。

  • List<T>可以包含指定类型的元素。它提供编译时类型检查,并且不执行装箱/拆箱,因为它是泛型的。

  • 可以使用Add(),AddRange()方法或collection-initializer(集合初始化器)语法添加元素。

  • 可以通过传递索引来访问元素,例如myList[0]。索引从零开始。

  • List<T>与ArrayList相比,执行速度更快,出错更少。

List<int> primeNumbers = new List<int>();
primeNumbers.Add(1); // 使用add()方法添加元素
primeNumbers.Add(3);
primeNumbers.Add(5);
primeNumbers.Add(7);

var cities = new List<string>();
cities.Add("New York");
cities.Add("London");
cities.Add("Mumbai");
cities.Add("Chicago");
cities.Add(null);// 引用类型列表允许为null

//使用collection-initializer语法添加元素
var bigCities = new List<string>()
                    {
                        "New York",
                        "London",
                        "Mumbai",
                        "Chicago"                    
                    };

 

三、泛型

参考文章:https://www.cainiaojc.com/csharp/csharp-generics.html

在C#中,泛型意味着不特定于特定数据类型。

C#允许您使用 type 参数并且不使用特定数据类型来定义泛型类,接口,抽象类,字段,方法,静态方法,属性,事件,委托和运算符。

类型参数是在创建泛型类型的实例时指定的特定类型的占位符。

通过在类型名称后的尖括号中指定类型参数来声明泛型,例如 TypeName<T>,

这里 T 是类型参数。

定义泛型:

class DataStore<T>
{
    public T Data { get; set; }
}

定义多个类型参数的泛型

class KeyValuePair<TKey, TValue>
{
    public TKey Key { get; set; }
    public TValue Value { get; set; }
}

实例化泛型:

DataStore<string> store = new DataStore<string>();

为不同的对象指定不同的数据类型:

DataStore<string> strStore = new DataStore<string>();
strStore.Data = "Hello World!";
//strStore.Data = 123; // 编译时错误

DataStore<int> intStore = new DataStore<int>();
intStore.Data = 100;
//intStore.Data = "Hello World!"; // 编译时错误

KeyValuePair<int, string> kvp1 = new KeyValuePair<int, string>();
kvp1.Key = 100;
kvp1.Value = "Hundred";

KeyValuePair<string, string> kvp2 = new KeyValuePair<string, string>();
kvp2.Key = "IT";
kvp2.Value = "Information Technology";

 

四、创建自己的List列表使用索引器访问

 
 
 
using System;
using System.Collections.Generic;
using System.Text;

namespace _20_MyList列表
{
    class MyList<T>
    {
        private T[] data = new T[0];//data null
        //引用类型 new 
        //MyClass mc ;=null

        private int count = 0;// 元素个数 数据个数

        public int Capacity
        {
            get
            {
                return data.Length;
            }
        }
        public int Count
        {
            get
            {
                return count;
            }
        }

        public void Add(T item)
        {
            if (data.Length == 0)
            {
                data = new T[4];
            }

            //添加元素之前 ,先判断数组是否已经满
            if (data.Length == count)
            {
                T[] temp = new T[count * 2];
                for(int i = 0; i < data.Length; i++)
                {
                    temp[i] = data[i];
                }
                data = temp;
            }

            data[count] = item;
            count++;
        }

        public T this[int index]
        {
            get
            {
                if(index<0 || index > count - 1)
                {
                    throw new ArgumentOutOfRangeException("索引参数超出范围了");
                }

                return data[index];
            }
            set
            {
                data[index] = value;
            }
        }

        public void Insert(int index,T item)
        {
            if (index < 0 || index > count - 1)
            {
                throw new ArgumentOutOfRangeException("索引参数超出范围了");
            }

            for(int i = count - 1; i > index - 1; i--)
            {
                // count-1     index
                data[i + 1] = data[i];
            }
            data[index] = item;
            count++;
        }
        public void RemoveAt(int index)
        {
            if (index < 0 || index > count - 1)
            {
                throw new ArgumentOutOfRangeException("索引参数超出范围了");
            }
            for(int i = index + 1; i < count; i++)
            {
                // index+1   count-1
                data[i - 1] = data[i];
            }
            count--;
        }
        public int IndexOf(T item)
        {
            int index = -1;

            for(int i = 0; i < count; i++)
            {// ToString Equals
                if (item.Equals(data[i]) )
                {
                    index = i;break;
                }
            }
            return index;
        }

        public int LastIndexOf(T item)
        {
            int index = -1;

            for (int i=count-1;i>=0;i--)
            {// ToString Equals
                if (item.Equals(data[i]))
                {
                    index = i; break;
                }
            }
            return index;
        }

        public void Sort()
        {
            Array.Sort(data, 0, count);
        }
    }
}

使用示例:

using System;
using System.Collections.Generic;

namespace _20_MyList列表
{
    class Program
    {
        static void Main(string[] args)
        {

            MyList<int> list = new MyList<int>();

            //Console.WriteLine(list.Capacity);
            list.Add(1);
            list.Add(2);
            list.Add(3);
            list.Add(4);
            list.Add(5);
            list.Add(4);

            list.Insert(2, 100);
            for (int i = 0; i < list.Count; i++)
            {
                Console.Write(list[i] + " ");
            }
            Console.WriteLine();

            list.RemoveAt(3);
            for (int i = 0; i < list.Count; i++)
            {
                Console.Write(list[i] + " ");
            }
            Console.WriteLine();

            Console.WriteLine(list.IndexOf(4));
            Console.WriteLine(list.LastIndexOf(4));
            list.Sort();
            for (int i = 0; i < list.Count; i++)
            {
                Console.Write(list[i] + " ");
            }
            Console.WriteLine();

            Program p1 = new Program();
            Program p2 = new Program();
            Console.WriteLine(p1.GetHashCode());
            Console.WriteLine(p2.GetHashCode());
            Console.WriteLine(p1.Equals(p2));

        }
        public override int GetHashCode()
        {
            return 100;
        }

    }
}