C#中的重要接口_1

来源:互联网 发布:java 购票系统demo 编辑:程序博客网 时间:2024/05/22 15:11

1. IDisposable

    理解此方法protectedvirtual void Dispose(bool disposing)

   分三种情况: 1)是用户正常调用了Dispose方法并且调用了GC.SuppressFinalize(this)方法则GC就将此对象从finalization queue中移出去,当GC发生时就不会调用对象的析构

                            函数或者Finalize方法以避免重复释放非托管资源。

                        2)用户正常调用了Dispose方法但没有调用GC.SuppressFinalize(this)方法。Dispose方法意味着非托管资源已经释放了,没有调用SuppressFinalize方法意味着

                             GC会调用析构函数,此时这种设计也可以保证析构函数不会做任何事即也避免重复释放非托管资源。

                        3)用户没有正常调用Dispose方法。意味着非托管资源没有释放。GC运行时将会调用析构函数来释放非托管资源。

2. Equals() 与 相等运算符(==)

   ==

   对于值类型,如果对象的值相等,则相等运算符 (==) 返回 true,否则返回 false。对于string 以外的引用类型,如果两个对象引用同一个对象,则 == 返回 true。

    对于 string 类型,== 比较字符串的值。

   Equals方法

   1) The type of comparison between the current instance and theobj parameter depends on whether the current instance is a reference type or a value type. If the current instance is a reference type, theEquals(Object) method tests for reference equality, and a call to theEquals(Object) method is equivalent to a call to theReferenceEquals method.

   2) Derived classes frequently override the Object.Equals(Object) method to implement value equality.

   意味着引用类型比较的是是否指向同一个对象。开发人员经常override这个方法来实现自定义的比较。比如两个对象的属性相同则这两个对象相等。

  

Follow these guidelines when overriding Equals(Object):

  • Types that implement IComparable must overrideEquals(Object).

  • Types that override Equals(Object) must also overrideGetHashCode; otherwise, hash tables  might not work correctly.

  • If your programming language supports operator overloading and you overload the equality operator for a given type, you must also override theEquals(Object) method to return the same result as the equality operator. This  helps ensure that class library code that usesEquals (such asArrayList andHashtable) behaves in a manner that is consistent with the way the equality operator is used by application code.

 

 

 

原创粉丝点击