F#类层次结构比较

时间:2011-07-16 12:03:51

标签: f#

解决此问题的最佳方法是什么? 这是F#中的一个简单的类层次结构:

[<AbstractClass>]
type BaseClass (name: string) = 
  member this.Name with get() = name

type FooClass (n, i: int) =
  inherit BaseClass (n)
  member this.Num with get() = i

type BarClass (n) = inherit BaseClass (n)

随着项目的进展,我将需要添加到这个层次结构中。 我需要通过检查这些类的实例是否相同并且Name具有相同的值(以及Num的{​​{1}}的相同值)来等同这些类的实例,所以ReferenceEquals不会削减它。做这个的最好方式是什么?我是否应该FooClass继承IComparable,如果是,那么我应该如何处理从BaseClass继承的类型并有额外的字段来检查?另一种方法是创建一个IComparer类来检查每个不同的类,但我真的希望代码在适当的类而不是在比较器中

1 个答案:

答案 0 :(得分:3)

我相信在基类上重写equals,然后通过利用基类实现来覆盖每个子类的equals是.NET OO中的标准方法:

[<AbstractClass>]
type BaseClass (name: string) = 
  member this.Name with get() = name
  override this.Equals(other:obj) =
    match other with
    | :? BaseClass as other ->
        other.Name = this.Name
    | _ -> false


type FooClass (n, i: int) =
  inherit BaseClass (n)
  member this.Num with get() = i
  override this.Equals(other:obj) =
    match other with
    | :? FooClass as other when base.Equals(other) -> //check type equality with this, and base equality
        other.Num = this.Num //check the additional properties for this supertype
    | _ -> false

type BarClass (n, i: bool) =
  inherit BaseClass (n)
  member this.Truth with get() = i
    override this.Equals(other:obj) =
    match other with
    | :? BarClass as other when base.Equals(other) ->
        other.Truth = this.Truth
    | _ -> false

let f1 = FooClass("Foo", 1)
let f2 = FooClass("Foo", 1)
f1 = f2 //true
let f3 = FooClass("Foo", 2)
f1 = f3 //false

//polymorphism in action (bc1 BaseClass will use sub class override)
let checkBaseClassesForEquality (bc1:BaseClass) (bc2:BaseClass) =
    bc1 = bc2

checkBaseClassesForEquality f1 f2 //true
checkBaseClassesForEquality f1 f3 //false