简体   繁体   English

vb.net和接口实现

[英]vb.net and interface implementation

I want that each class in a certain namespace implement IEquatable(Of thatClass) and its corresponding GetHashCode . 我希望某个命名空间中的每个类都实现IEquatable(Of thatClass)及其对应的GetHashCode

Namespace DAO
    Public Class Product : Implements IEquatable(Of Product)

        Shadows Function Equals(ByVal other As Product) As Boolean Implements IEquatable(Of Product).Equals
        Shadows Function GetHashCode() As Integer
    End Class

End Namespace

I can just "remember" to implement the two methods but that would be poor practice. 我可以“记住”实现这两种方法,但这将是一种不好的做法。

I could write an interface IDao and again "remember" to let all the classes implement that interface. 我可以编写一个接口IDao,然后再次“记住”以让所有类都实现该接口。 But an interface can't implement another interface. 但是一个接口不能实现另一个接口。

Public Interface IDao : Implements IEquatable ' <---- NO!

Ok, so I could create an abstract class (bad, the Dao classes won't be able to inherit from other classes) and again remember to let all the classes inherit from it: 好的,所以我可以创建一个抽象类(糟糕的是,Dao类将无法从其他类继承),并再次记住要让所有类都从其继承:

Public MustInherit Class DaoBase : Implements IEquatable(Of DaoBase)

        MustOverride Shadows Function Equals(ByVal other As DaoBase) As Boolean Implements IEquatable(Of DaoBase).Equals
        MustOverride Shadows Function GetHashCode() As Integer

    End Class

 Public Class Product
        Inherits DaoBase

    Overrides Function Equals(ByVal other As DaoBase) As Boolean
            Return ??? 
    End Function

Now the parameter in Equals is a DaoBase, not a Product. 现在,等于中的参数是DaoBase,而不是产品。 I could cast, but... 我可以投,但是...

Or I could generalize the DaoBase like: 或者我可以将DaoBase概括为:

  Public MustInherit Class DaoBase(Of T) : Implements IEquatable(Of T)

        MustOverride Shadows Function Equals(ByVal other As T) As Boolean Implements IEquatable(Of T).Equals
        MustOverride Shadows Function GetHashCode() As Integer

    End Class

But that means a different DaoBase will be created for each inheriting class. 但这意味着将为每个继承的类创建一个不同的DaoBase。

Is there a way to declare DaoBase non-generic and have the subclasses handle the right types? 有没有一种方法可以声明DaoBase非泛型, 让子类处理正确的类型?

Nice to have: force each class in a namespace to implement an interface by contract. 很高兴:强制命名空间中的每个类通过协定实现接口。 So I don't have to remember ;) 所以我不必记住;)

An interface cannot implement another interface, but it can inherit from another interface. 一个接口不能实现另一个接口,但是可以从另一个接口继承。 The following works: 以下作品:

Public Interface IDao 
    Inherits IEquatable 

End Interface

So you could apply your initial thought with this approach 因此,您可以使用这种方法来应用您的初步想法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM