VB.Net - 如何支持隐式类型转换以及自定义相等

时间:2008-09-30 00:35:06

标签: vb.net clr type-conversion

已修复:请参见底部的注释

我正在实现一个支持两个功能的泛型类,隐式类型转换和自定义相等运算符。好吧,它也支持IN-equality,如果它那样的话。

1) if ( "value" = myInstance ) then ...
2) Dim s As String = myInstance
3) Dim s As String = CType(myInstance,String)

我遇到的问题是,如果我支持#2,隐式转换,那么我无法使我的等式运算符起作用,因为他们抱怨没有转换是最具体的。

我得到的错误就是这个(为简洁起见,简化了一下):

Overload resolution failed because no accessible '=' is most specific for these arguments:
    'Public Shared Operator =(obj As MyClass, data As String) As Boolean': Not most specific.
    'Public Shared Operator =(data As String, obj As MyClass) As Boolean': Not most specific.
    'Public Shared Operator =(obj1 As MyClass, obj2 As MyClass) As Boolean': Not most specific.

实现这一目标的最佳方式是什么。同样重要的是,我应该遗漏什么?我已实施以下转化

Operator =(ByVal data As String,    ByVal obj  As classType) As Boolean (and <>)
Operator =(ByVal obj  As classType, byval data As String) As Boolean (and <>)
Operator =(ByVal obj1 As classType, ByVal obj2 As classType) As Boolean (and <>)
Equals(obj as Object) as Boolean
Equals(compareTo as classType ) as Boolean
Equals(compareTo as String) as Boolean
Widening Operator CType(ByVal source As String) As classType
Widening Operator CType(ByVal source As classType) as String
Narrowing Operator CType(ByVal inst As classType) As dataType

在我的扩展运算符中,我做了一些反射,这就是为什么我希望能够在使用左侧的字符串进行比较或赋值时将DOWN隐式转换为String。

A) SomeObject.StringPropertySetter = MyClass

修复(编辑)

我在实施的内容上走得太远,因为我不明白发生了什么。基类型(即字符串/双/ guid)之间的比较通过扩展ctype(...)作为String(或Guid等)运算符进行。最后,我刚刚实现了这些函数,除了从类到基类型实例的赋值之外,我的所有测试用例仍然通过

Public Class MyClass(Of BaseType)

    Widening Operator CType(ByVal source As dataType) As MyClass 
    Widening Operator CType(ByVal source As MyClass) As dataType //conv between inst & base
    Equals()  // for datatype, classType, object
    Operator <>(MyClass,MyClass) // for comparison between two instances
    Opeator   =(MyClass,MyClass)    

评论是c风格,但代码是vb.net

当然课程比这复杂一点,但是这给了我所需要的一切:)

1 个答案:

答案 0 :(得分:2)

您不应该覆盖=运算符。如果您对stringint等类型进行隐式转换,则让默认的相等运算符接管。

作为一般规则,如果您需要自定义类的相等性,则应覆盖Equals(object)方法。