1. ICloneable
说明:浅拷贝指仅拷贝值类型,深拷贝指拷贝值类型和引用类型
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee(128, "Tim");
emp1.HomeAddress = new Address("Guangdong", "Guangzhou", "Haizhu");
Employee emp2 = (Employee)emp1.Clone();
emp1.ShowInfo();
emp2.ShowInfo();
emp2.WorkNum = 200;
emp2.Name = "Snake";
emp2.HomeAddress.Street = "Tianhe";
emp1.ShowInfo();
emp2.ShowInfo();
Console.ReadLine();
}
}
class Employee : ICloneable
{
public int WorkNum;
public string Name;
public Address HomeAddress;
public Employee(int workNum, string name)
{
this.WorkNum = workNum;
this.Name = name;
}
public void ShowInfo()
{
Console.WriteLine("WorkNum:{0} Name:{1} HomeAddres:{2} ", this.WorkNum, this.Name, this.HomeAddress);
}
// shallow cloning
//public object Clone()
//{
// Employee emp = new Employee(this.WorkNum, this.Name);
// emp.HomeAddress = this.HomeAddress;
// return emp;
//}
// deep cloning
public object Clone()
{
Employee emp = new Employee(this.WorkNum, this.Name);
emp.HomeAddress = new Address(this.HomeAddress.Province, this.HomeAddress.City, this.HomeAddress.Street);
return emp;
}
}
class Address
{
public string Province;
public string City;
public string Street;
public Address(string province, string city, string street)
{
this.Province = province;
this.City = city;
this.Street = street;
}
public override string ToString()
{
return string.Format("{0} {1} {2}", this.Province, this.City, this.Street);
}
}
2. ICompareable
定义一种特定于类型的通用比较方法,值类型或类通过实现此方法对其实例进行排序。
class Program
{
static void Main(string[] args)
{
Complex num1 = new Complex(2, 3);
Complex num2 = new Complex(3, 2);
Console.WriteLine("num1 = {0}", num1.ToString());
Console.WriteLine("num2 = {0}", num2.ToString());
try
{
//Console.WriteLine("num1 CompareTo num2 ? {0}", num1.CompareTo(num2));
Console.WriteLine("num1 CompareTo num2 ? {0}", num1.CompareTo("haha"));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
class Complex : IComparable
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public double Module()
{
return Math.Sqrt(Math.Pow(this.real, 2) + Math.Pow(this.imaginary, 2));
}
public override string ToString()
{
return string.Format("{0} + {1}i", this.real, this.imaginary);
}
#region implement IComparable interface
public int CompareTo(object obj)
{
if (obj is Complex)
{
Complex other = (Complex)obj;
return this.Module().CompareTo(other.Module());
}
throw new ArgumentException("Object is not an Complex.");
}
#endregion
}
3. ICompareableGeneric
class Program
{
static void Main(string[] args)
{
Complex num1 = new Complex(2, 3);
Complex num2 = new Complex(3, 2);
Complex num3 = null;
Console.WriteLine("num1 = {0}", num1.ToString());
Console.WriteLine("num2 = {0}", num2.ToString());
try
{
//Console.WriteLine("num1 CompareTo num2 ? {0}", num1.CompareTo(num2));
Console.WriteLine("num1 CompareTo num2 ? {0}", num1.CompareTo(num3));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
class Complex : IComparable<Complex>
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public double Module()
{
return Math.Sqrt(Math.Pow(this.real, 2) + Math.Pow(this.imaginary, 2));
}
public override string ToString()
{
return string.Format("{0} + {1}i", this.real, this.imaginary);
}
#region implement IComparable<Complex> generic interface
public int CompareTo(Complex other)
{
if (other == null) throw new NullReferenceException();
return this.Module().CompareTo(other.Module());
}
#endregion
4. IEquatable
定义一个通用的方法,由值类型或类实现以创建类型特定的方法,用于确定实例间的相等性。
class Program
{
static void Main(string[] args)
{
Complex num1 = new Complex(2, 3);
Complex num2 = new Complex(2, 3);
Complex num3 = null;
Console.WriteLine("num1 = {0}", num1.ToString());
Console.WriteLine("num2 = {0}", num2.ToString());
try
{
Console.WriteLine("num1 Equals num2 ? {0}", num1.Equals(num2));
Console.WriteLine("num1 Equals num2 ? {0}", num1.Equals("haha"));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
class Complex : IEquatable<Complex>
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public double Module()
{
return Math.Sqrt(Math.Pow(this.real, 2) + Math.Pow(this.imaginary, 2));
}
public override string ToString()
{
return string.Format("{0} + {1}i", this.real, this.imaginary);
}
#region implement IEquatable<Complex> interface
public override bool Equals(object other)
{
return Equals(other as Complex);
}
public bool Equals(Complex other)
{
if (other == null) return false;
return (this.real == other.real && this.imaginary == other.imaginary);
}
#endregion
}
5. IFormattable
提供将对象的值格式化为字符串表示形式的功能。
class Program
{
static void Main(string[] args)
{
Complex num1 = new Complex(2, 3);
try
{
Console.WriteLine("num1 = {0}", num1);
Console.WriteLine("num1 = {0:N}", num1);
Console.WriteLine("num1 = {0:X}", num1);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
class Complex : IFormattable
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public double Module()
{
return Math.Sqrt(Math.Pow(this.real, 2) + Math.Pow(this.imaginary, 2));
}
#region implement IFormattable interface
public override string ToString() { return ToString(null, null); }
public string ToString(string format, IFormatProvider fp)
{
// If no format is passed, display like this: x + yi
if (format == null) return string.Format("{0} + {1}i", this.real, this.imaginary);
// For "N" formatting, display like this: (x,y)
if (format == "N") return string.Format("({0},{1})", this.real, this.imaginary);
// For any unrecognized format, throw an exception.
throw new FormatException(string.Format("Invalid format string: '{0}'.", format));
}
#endregion
}
6. Destructor
class Program
{
static void Main(string[] args)
{
Create();
Console.WriteLine("After DemoClass created.");
Console.ReadLine();
GC.Collect();
Console.ReadLine();
}
static void Create()
{
DemoClass demo = new DemoClass();
}
}
class DemoClass
{
public DemoClass()
{
Console.WriteLine("Constructor is called.");
}
~DemoClass()
{
Console.WriteLine("Destructor is called.");
}
}
7. IDisposeable
8. IEnumerator
支持对非泛型集合的简单迭代。
所有继承了IEnumerable的类,要使用foreach迭代器时,就需要使用该方法。因此也只有实现了该接口的类才可以使用foreach。
公共属性
名称 | 说明 | |
| 获取集合中的当前元素。 |
公共方法
名称 | 说明 | |
| 将枚举数推进到集合的下一个元素。 | |
| 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。 |
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
public object Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
9. IEnumerable
返回一个循环访问集合的枚举器。
C# 语言的 foreach 语句(在 Visual Basic 中为 For Each)隐藏了枚举数的复杂性。因此,建议使用 foreach,而不是直接操作枚举数。
枚举数可用于读取集合中的数据,但不能用于修改基础集合。
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new PeopleEnum(_people);
}
}
10. ICollection
实现ICollection的范例
1 using System;
2 using System.Collections;
3
4 namespace Relaction.Collections
5 {
6 /// <summary>
7 ///
8 /// </summary>
9 public class MyCollections:ICollection
10 {
11 private string[] _list;
12 private object _root = new object();
13 public MyCollections()
14 {
15 _list = new string[3]{"1","2","3"};
16 }
17 #region ICollection 成员
18
19 public bool IsSynchronized
20 {
21 get
22 {
23 return true;
24 }
25 }
26
27 public int Count
28 {
29 get
30 {
31 return _list.Length;
32 }
33 }
34
35 public void CopyTo(Array array, int index)
36 {
37 _list.CopyTo(array,index);
38 }
39
40 public object SyncRoot
41 {
42 get
43 {
44 return _root;
45 }
46 }
47
48 #endregion
49
50 #region IEnumerable 成员
51
52 public IEnumerator GetEnumerator()
53 {
54 return _list.GetEnumerator();
55 }
56
57 #endregion
58 }
59 }
60
客户代码:
1 private void button7_Click(object sender, System.EventArgs e)
2 {
3 Relaction.Collections.MyCollections c = new Relaction.Collections.MyCollections();
4 foreach(string s in c)
5 {
6 label1.Text += s.ToString();
7 }
8 }