Skip to main content
 首页 » 编程设计

c#之在 VB.NET 中使用 ByRef 实现和传递接口(interface)方法

2024年02月24日24zdz8207

我有一个这样定义的 C# 接口(interface):

public interface IMenuSecurityService 
{ 
    void SetSecurityFlags(List<MenuItem> items); 
} 

我需要在 VB.NET 类中实现此接口(interface)。当我使用 ByVal 传递的 items 参数实现 SetSecurityFlags 方法时,它会编译。

Public Sub SetSecurityFlags(ByVal items As List(Of L1.Common.Model.MenuItem)) Implements IMenuSecurityService.SetSecurityFlags 
    ' Do some work 
End Sub 

当我尝试通过使用 ByRef 传递的 items 参数来实现它时,出现以下编译器错误:

Class 'UserRights' must implement 'Sub SetSecurityFlags(items As System.Collections.Generic.List(Of Model.MenuItem))' for interface

Public Sub SetSecurityFlags(ByRef items As List(Of L1.Common.Model.MenuItem)) Implements IMenuSecurityService.SetSecurityFlags 
    ' Do some work 
End Sub 

我似乎无法弄清楚这一点。 VB.NET 不支持这个还是我做错了什么?

请您参考如下方法:

这不是 VB 与 C# 的问题 - 这是您的签名错误的问题。

您的方法没有实现接口(interface),因为接口(interface)方法有一个按值参数,而您的方法有一个按引用参数。如果你在 C# 中这样做,你会遇到同样的问题:

interface IFoo 
{ 
    void Bar(int x); 
} 
 
class Foo : IFoo 
{ 
    public void Bar(ref int x) {} 
} 

编译错误:

Test.cs(8,7): error CS0535: 'Foo' does not implement interface member 
    'IFoo.Bar(int)' 

您还没有解释为什么您认为需要使用 ByRef参数 - 当涉及像 List<T> 这样的引用类型时,您可能并不真正理解按引用传递与按值传递语义。 .看看my article有关该主题的更多信息。