固定:见底部注释
我正在实现一个支持两个特性的泛型类,隐式类型转换和自定义相等运算符。好吧,它也支持 IN 平等,如果它这样做的话。
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
修复(编辑)
我在实施的过程中做得太过火了,因为我不明白发生了什么。基本类型(即 string/double/guid)之间的比较通过扩展 ctype(...) as 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
当然,这门课比这要复杂一些,但这给了我我需要的一切:)