首Html代码

学有所用,不然就失去意义。

子标题

导航

在 Visual C# .NET 中实现自定义集合

View Code
using System;
using System.Collections;

class TempClass
{
    
public class CustomCollection : ICollection
    {

        
private int[] intArr = { 159 };
        
private int Ct;

        
public CustomCollection()
        {
            Ct 
= 3;
        }
        
void ICollection.CopyTo(Array myArr, int index)
        {

            
foreach (int i in intArr)
            {
                myArr.SetValue(i, index);
                index 
= index + 1;
            }

        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            
return new Enumerator(intArr);
        }
        
//The IsSynchronized Boolean property returns True if the 
        
//collection is designed to be thread safe; otherwise, it returns False.
        bool ICollection.IsSynchronized
        {
            
get
            {
                
return false;
            }
        }

        
//The SyncRoot property returns an object, which is used for synchronizing 
        
//the collection.This returns the instance of the object or returns the 
        
//SyncRoot of other collections if the collection contains other collections.
        
// 
        object ICollection.SyncRoot
        {
            
get
            {
                
return this;
            }
        }

        
//The Count read-only property returns the number 
        
//of items in the collection.
        int ICollection.Count
        {
            
get
            {
                
return Ct;
            }
        }
    }
    
public class Enumerator : IEnumerator
    {
        
private int[] intArr;
        
private int Cursor;
        
public Enumerator(int[] intarr)
        {
            
this.intArr = intarr;
            Cursor 
= -1;
        }
        
void IEnumerator.Reset()
        {
            Cursor 
= -1;
        }
        
bool IEnumerator.MoveNext()
        {
            
if (Cursor < intArr.Length)
                Cursor
++;

            
return (!(Cursor == intArr.Length));
        }
        
object IEnumerator.Current
        {
            
get
            {
                
if ((Cursor < 0|| (Cursor == intArr.Length))
                    
throw new InvalidOperationException();
                
return intArr[Cursor];
            }
        }
    }
    
static void Main()
    {
        CustomCollection MyCol 
= new CustomCollection();

        
foreach (object MyObj in MyCol)
            Console.WriteLine(MyObj.ToString());
    }
}

posted on 2011-04-22 10:23  tssing  阅读(409)  评论(0编辑  收藏  举报

页脚Html代码