.net - Vb.net接口(interface),make方法只接受相同类型的实例作为参数

标签 .net vb.net generics types

我试图在我的 vb.net 接口(interface)中定义一个方法,该方法只接受从同一接口(interface)继承的对象,并且与接收方法调用的实例属于同一类。这在 vb.net 中可能吗?

下面我尝试用(无效的)泛型类型约束来说明我希望做什么:

Public Interface IFoo

   CompareStuff(Of T as sametype)(obj as T) as Boolean

End Interface

最佳答案

您正在寻找Curiously recurring template pattern

我对 VB 有点生疏,所以这里是用 C# 编写的

public interface IFoo<T>
    where T : IFoo<T>
{
    bool CompareStuff(T obj);
}

然后你就这样实现

public class Foo : IFoo<Foo>
{
    bool CompareStuff(Foo obj);
}

查看this article埃里克·利珀特(Eric Lippert)介绍了这一点。特别注意他说的结尾:

My advice is to think very hard before you implement this sort of curious pattern in C#; do the benefits to the customer really outweigh the costs associated with the mental burden you're placing on the code maintainers?

关于.net - Vb.net接口(interface),make方法只接受相同类型的实例作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11307652/

相关文章:

Java泛型类型参数混淆

generics - 如何在 Dart 中使用镜像获取泛型类型变量的具体类型?

c# - 使用 System.Type 调用泛型方法

c# - 与 WCF 服务共享领域模型

c# - NuGet 以及处理框架和核心的更新

c# - 将 gRPC 服务绑定(bind)到 aspnetcore 中的特定端口

c# - 错误 : '<method1>' and '<method2>' cannot overload each other

c# - 在数据库自动增加列中。如果值达到最大值怎么办

c# - 由于泛型类型推断的限制,无法使用泛型来改进 API

.net - Visual Basic圆形进度条