gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:38:36 33 4
gpt4 key购买 nike

已修复:见底部注释

我正在实现一个支持两个功能的通用类,即隐式类型转换和自定义相等运算符。嗯,它也支持 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

在我的加宽运算符中,我做了一些反射(reflection),这就是为什么我希望在对左侧的字符串进行比较或赋值时能够将 DOWN 隐式转换为字符串。

A) SomeObject.StringPropertySetter = MyClass

修复(编辑)

我在实现方面做得太过火了,因为我不明白发生了什么。基本类型(即字符串/ 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

当然类(class)比那复杂一点,但这给了我我需要的一切:)

最佳答案

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

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

关于VB.Net - 如何支持隐式类型转换和自定义相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/151318/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com