自定义集合

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

namespace CustomCollection
{
    
class Program
    {
        
static void Main(string[] args)
        {

            StudentCollection sc 
= new StudentCollection();
            sc.Add(
new Student("小王",22));
            sc.Add(
new Student("小张",33));

            Student s 
= new Student("张三",36);
            sc.Insert(
1, s);
            sc.Remove(s);

            
foreach (Student student in sc)
            {
                Console.WriteLine(
" Name : {0} \tAge : {1}", student.Name, student.Age);
            }

            Console.ReadLine();

        }
    }

    
class Student
    {
        
private string _name;

        
public string Name
        {
            
get { return _name; }
            
set { _name = value; }
        }
        
private int _age;

        
public int Age
        {
            
get { return _age; }
            
set { _age = value; }
        }

        
public Student(string name, int age)
        {
            
this._name = name;
            
this._age = age;
        }
    }

    
class StudentCollection : CollectionBase
    {
        
public StudentCollection()
        { 
        }

        
public StudentCollection(Student[] students)
        {
 
        }

        
public int Add(Student student)
        {
            
return base.List.Add(student);
        }

        
public void AddRange(Student[] students)
        {
            
if (students == null)
                
throw new ArgumentNullException("Argument students is null.");
            
for (int i = 0; i < students.Length; i++)
            {
                
this.Add(students[i]);
            }
        }

        
public bool Contains(Student student)
        {
            
return base.List.Contains(student);
        }

        
public void CopyTo(Student[] students, Int32 index)
        {
            
base.List.CopyTo(students, index);
        }

        
public void Insert(int index,Student student)
        {
            
base.List.Insert(index, student);
        }

        
public void Remove(Student student)
        {
            
base.List.Remove(student);
        }

        
public Student this[int index]
        {
            
get
            {
                
return (Student)base.List[index];
            }
            
set
            {
                
base.List[index] = value;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/ulex/p/1731882.html