我试图在我的 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/