c#学习心得(2)
1.foreach与IEnumerable和IEnumerator的结合使用?????
using System; using System.Collections; class Program { static void Main(string[] args) { TestIEnumerable test = new TestIEnumerable(); foreach (string str in test) { Console.WriteLine(str); } Console.ReadKey(); } } class TestIEnumerable : IEnumerable { private string[] _item; public TestIEnumerable() { _item = new string[] { "1","2","3","4" }; } public string this[int index] { get { return _item[index]; } } public IEnumerator GetEnumerator() { return new EnumeratorActualize(this); } class EnumeratorActualize : IEnumerator { private int index; private TestIEnumerable _testEnumerable; private object currentObj; public EnumeratorActualize(TestIEnumerable testEnumerable) { _testEnumerable = testEnumerable; currentObj = new object(); index = -1; } public object Current { get { return currentObj; } } public bool MoveNext() { if (index < _testEnumerable._item.Length - 1) { index++; currentObj = _testEnumerable._item[index]; return true; } index = _testEnumerable._item.Length; return false; } public void Reset() { index = -1; } } }
2.IDisposable清除对象(接口)
using System; using System.Collections; public class MyClass: IDisposable { public MyClass() { Console.WriteLine("constructor"); } ~MyClass() { Console.WriteLine("destructor"); } public void Dispose() { Console.WriteLine("implementation of IDisposable.Dispose()"); } } public class MainClass { static void Main() { using (MyClass MyObject = new MyClass()) //using 关键字用于创建一个对象MyObject 该对象属于MyClass类 //当代吗分支到达using代码的闭花括号时,将自动撤销该对象 { } } }
enum 枚举
GetName与Format方法
using System; public enum LegalDoorStates { DoorStateOpen, DoorStateClosed } class DoorController { private LegalDoorStates CurrentState; public LegalDoorStates State { get { return CurrentState; } set { CurrentState = value; } } } class MainClass { public static void Main() { DoorController Door; string EnumName; Door = new DoorController(); Door.State = LegalDoorStates.DoorStateOpen; // EnumName = LegalDoorStates.GetName(typeof(LegalDoorStates), Door.State); EnumName = LegalDoorStates.Format(typeof(LegalDoorStates),1,"f");//g,x,d,f Console.WriteLine(EnumName); } }
CompareTo方法与检索所有枚举值
using System; public class MainClass { public enum Color { Red = 0, Orange, Yellow, Green, Blue, Indigo, Violet } static void Main() { Color MyColor; MyColor = Color.Green; Console.WriteLine("{0}", MyColor.CompareTo(Color.Red)); Console.WriteLine("{0}", MyColor.CompareTo(Color.Green)); Console.WriteLine("{0}", MyColor.CompareTo(Color.Violet));//CompareTo方法 比较 Array ValueArray; ValueArray = Color.GetValues(typeof(Color));//GetValue方法返回一个包含所有枚举值的数组 foreach (Color ColorItem in ValueArray) Console.WriteLine(ColorItem.ToString()); } }