我有一个接口(interface)I
,我刚刚决定弃用方法 OldMethod
(因为它的名字不好,因为我想要额外的参数,你命名它)并建议我库的用户使用NewMethod
反而。因此,我延长了 I
如下:
Interface I
<Obsolete("Use NewMethod instead.")>
Sub OldMethod()
Sub NewMethod()
End Interface
但是,现在我所有的类(class)实现
I
得到编译器警告:Class C
Implements I
' The following line yields warning BC40000
Public Sub OldMethod() Implements I.OldMethod
Throw New NotImplementedException()
End Sub
Public Sub NewMethod() Implements I.NewMethod
Throw New NotImplementedException()
End Sub
End Class
这对我来说没有意义:实现
I
(总体而言,它并没有过时),我需要实现 OldMethod
. C# 中的相应代码编译得非常好,并且不会产生警告:interface I
{
[Obsolete("Use NewMethod instead.")]
void OldMethod();
void NewMethod();
}
class Explicit : I
{
public void NewMethod() { throw new NotImplementedException(); }
public void OldMethod() { throw new NotImplementedException(); }
}
class Implicit : I
{
void I.NewMethod() { throw new NotImplementedException(); }
void I.OldMethod() { throw new NotImplementedException(); }
}
我知道我可以 suppress the warning in VB ,但是,通常,编译器警告表明您正在做一些不应该以这种方式完成的事情。
如何在 VB.NET 中实现具有过时成员的接口(interface)而不会收到过时警告?
最佳答案
从我的评论中充实这个答案。
实现类必须实现Obsolete
成员履行契约(Contract),但当接口(interface)方法标记为Obsolete
你 还必须将对应的方法标记为Obsolete
满足编译器执行Obsolete
不得使用成员(member)。
Public Interface I
<Obsolete("Use NewMethod instead.")>
Sub OldMethod()
Sub NewMethod()
End Interface
Public Class C
Implements I
<Obsolete("Use NewMethod instead.")>
Public Sub OldMethod() Implements I.OldMethod ' No warning
Throw New NotImplementedException()
End Sub
Public Sub NewMethod() Implements I.NewMethod
Throw New NotImplementedException()
End Sub
End Class
虽然与这个特定问题并不完全相关,但在研究时我发现了这个 blog post by Grant Winney解释为什么在接口(interface)成员本身(以及实现成员)上标记过时的成员是个好主意
关于vb.net - 如何在 VB.NET 中使用过时的方法实现接口(interface)而不抑制警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52781754/