.net - 在 VB.NET 中使用单个属性实现多个接口(interface)

标签 .net vb.net interface implements

启动时,我将所有 app.config 值加载到名为 ConfigValues 的类中.我的数据库只需要其中一些,所以我有一个 IDatabaseConfig只指定它需要的参数的接口(interface)。这样,当我使用构造函数注入(inject)创建数据库连接类时,我可以要求它传递任何实现 IDatabaseConfig 的东西。 .

我想做的是在 ConfigValues 上声明多个接口(interface)类并允许某些属性同时实现多个契约(Contract)。

这是一个小代码示例:

Public Interface IAppConfig
    Property Server As String
    Property ErrorPath As String
End Interface

Public Interface IDatabaseConfig
    Property Server As String
End Interface

Public Class ConfigValues
    Implements IAppConfig
    Implements IDatabaseConfig

    Public Property ErrorPath As String Implements IAppConfig.ErrorPath

    'need different syntax - does not compile:
    Public Property Server As String Implements IAppConfig.Server, 
                                     Implements IDatabaseConfig.Server

End Class

在 VB.NET 中,有没有办法指定单个属性满足多个接口(interface)的约定?

这与 SO 上的这两个问题完全相反,它们试图将相同的接口(interface)名称拆分为两个不同的属性。
  • Implementing 2 Interfaces with 'Same Name' Properties
  • How to implement an interface in VB.Net when two methods have the same name but different parameters


  • 作为一种笨拙的解决方法,我可以让两个属性都引用相同的支持属性,但我必须更改其中至少一个的属性名称,这会更改 API。

    Private _server As String
    Public Property ServerForApp As String Implements IAppConfig.Server
        Get
            Return _server
        End Get
        Set(value As String)
            _server = value
        End Set
    End Property
    Public Property ServerForDatabase As String Implements IDatabaseConfig.Server
        Get
            Return _server
        End Get
        Set(value As String)
            _server = value
        End Set
    End Property
    

    最佳答案

    我认为你想要的得到支持,你只是语法错误:

    Public Class ConfigValues
        Implements IAppConfig
        Implements IDatabaseConfig
    
        Public Property ErrorPath As String Implements IAppConfig.ErrorPath
    
        Public Property Server As String Implements IAppConfig.Server, 
                                                    IDatabaseConfig.Server
    
    End Class
    

    关于.net - 在 VB.NET 中使用单个属性实现多个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21635548/

    相关文章:

    c# - 如何使用 LINQ 确保多个集合具有相同的项目计数

    vb.net - 对于一个使用继承的新 VB.NET 程序员来说,花 10 到 20 小时编写程序是怎样的呢?

    vb.net - 用于自动添加事件委托(delegate)方法的 Visual Studio 快捷方式

    c# - 接口(interface)类型转换

    java - Connection、Statement 等预定义接口(interface)的抽象方法如何在没有主体的情况下执行某些任务?

    c# - ListView 项目在 winform 中选择

    .net - 从 .ebextensions 中的 Elastic Beanstalk 读取环境属性

    .net - 覆盖具有 ID 的对象的等于

    具有多个运行接口(interface)的机器上的 Linux 主机名解析

    c# - 区分 getter-only 属性和表达式主体属性?