首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从C#继承VB接口-移植代码

从C#继承VB接口-移植代码
EN

Stack Overflow用户
提问于 2018-05-08 10:57:03
回答 2查看 698关注 0票数 0

所以,我正在使用一个库(Coderr,对于熟悉它的人来说),它是用C#编写的,他们的例子也是这样。我的项目当然是在VB中进行的,我对实现他们的示例类的模板感到有点困惑。

他们现有的一个类的一个例子是这里

我试图手动移植它,但失败了,所以使用Telerik的C#到VB转换器。它输出看起来非常好的代码,只需经过一次调整,类本身就能工作得很好。除了继承条款。

我现在得到的密码是:

代码语言:javascript
复制
Namespace codeRR.Client.AspNet.CurrentUserContext    
    Public Class CurrentUserContext
        Inherits IContextInfoProvider

        Public Function Collect(ByVal context As IErrorReporterContext) As ContextCollectionDTO
            Dim CurrentUser As CurrentUser = CType(HttpContext.Current.Session("CurrentUser"), CurrentUser)
            If CurrentUser Is Nothing Then Return Nothing
            Dim converter = New ObjectToContextCollectionConverter()
            Dim collection = converter.Convert(Name, CurrentUser)
            Return If(collection.Properties.Count = 0, Nothing, collection)
        End Function

        Public ReadOnly Property Name As String
            Get
                Return "CurrentUser"
            End Get
        End Property
    End Class
End Namespace

非常类似于示例代码,但基本上返回了我的自定义对象。继承行在以下方面失败:

类只能从其他类继承。

这是有意义的,因为IContextInfoProvider是一个接口。我只想知道我在VB中是如何使用它的。我需要将类插入到接受IContextInfoProvider类型对象的函数中。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-08 11:06:34

这个错误给了你一个很好的指示是什么问题。虽然一个类可以从另一个类继承,但它不能从一个接口继承。

继承意味着得到类所包含的行为的一些实际实现,以及它的“签名”,而接口只是定义它的“签名”,期望在实现类中实现适当的行为,因此只能实现它。

所以,

代码语言:javascript
复制
Public Class CurrentUserContext
    Inherits IContextInfoProvider

应该是

代码语言:javascript
复制
Public Class CurrentUserContext
    Implements IContextInfoProvider
票数 3
EN

Stack Overflow用户

发布于 2018-05-08 11:29:50

类可以继承其他类,也可以实现接口。接口通常以大写I (如IContextInfoProvider )开头.

在C#中,类可以使用相同的语法实现接口或从另一个类继承:

代码语言:javascript
复制
// Implement an interface
public class CurrentUserContext : IContextInfoProvider

// Inherit from a class
public class CurrentUserContext : MyContextBaseClass

然而,在VB.Net中,实现接口的类或继承自另一个类的类采用两种不同的语法:

代码语言:javascript
复制
' Implement an interface
Public Class CurrentUserContext
    Implements IContextInfoProvider

' Inherit from a class
Public Class CurrentUserContext
    Inherits MyContextBaseClass

在您的示例中,您应该使用Implements而不是Inherits,因为您正在实现接口,而不是从类继承。

我希望这能把事情弄清楚!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50231940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档