2012-10-03 27 views
0

如何在一个继承类中为一个变量声明为该类所实现的接口之一的类型时使该类的属性可用?VB.Net和通过接口类型的变量访问

我到目前为止所做的工作是用关键字MustInherit创建抽象类MyAbstract,并在继承类MyInheritingClass中添加了继承,然后添加了抽象类的名称。现在,这一切都很好,但在我的继承类中,如果我在该类上创建了一个接口并在代码的其他地方使用该接口,那么我发现我无法从我的抽象类中看到用该界面。

我在这里做错了什么,或者有什么我需要做的吗?

一个例子是如下:

Public MustInherit Class MyAbstract 
    Private _myString as String 
    Public Property CommonString as String 
     Get 
      Return _myString 
     End Get 
     Set (value as String) 
      _myString = value 
     End Set 
    End Property 
End Class 

Public Class MyInheritingClass 
    Inherits MyAbstract 
    Implements MyInterface 

    Sub MySub(myParameter As MyInterface) 
     myParameter.CommonString = "abc" ' compiler error - CommonString is not a member of MyInterface. 
    End Sub 

    'Other properties and methods go here!' 
End Class 

所以,这是我在做什么,但是当我使用MyInterface,我看不到我的抽象类的属性!

+0

一个简单的例子将有助于说明您的问题 –

+0

请参阅编辑! – Andy5

+0

我假设你打算把'Implements MyInterface'或'Implements IMyInheritingClass'而不是'Implements MyInheritingClass'。一个类不能实现一个类 - 它只能实现一个接口。当然,一个班级无法实现所有的东西:) –

回答

7

除非我完全误解了你的问题,否则我不确定你为什么会被这种行为困惑。不仅如此,它应该如何工作,但这也是它在c#中的工作原理。例如:

class Program 
{ 
    private abstract class MyAbstract 
    { 
     private string _myString; 
     public string CommonString 
     { 
      get { return _myString; } 
      set { _myString = value; } 
     } 
    } 

    private interface MyInterface 
    { 
     string UncommonString { get; set; } 
    } 

    private class MyInheritedClass : MyAbstract, MyInterface 
    { 
     private string _uncommonString; 
     public string UncommonString 
     { 
      get { return _uncommonString; } 
      set { _uncommonString = value; } 
     } 
    } 

    static void Main(string[] args) 
    { 
     MyInterface test = new MyInheritedClass(); 
     string compile = test.UncommonString; 
     string doesntCompile = test.CommonString; // This line fails to compile 
    } 
} 

当您通过任何接口或基类的访问对象时,你将只能够访问由该接口或基类公开的成员。如果您需要访问MyAbstract的成员,则需要将该对象投射为MyAbstractMyInheritedClass。这两种语言都是如此。

+0

我听到你的声音,但是当我在ASP.NET应用程序的模型层(它是一个MVC Web应用程序)中构建一个函数时,我遇到了这个问题。在函数接口中,我写了Public Function SaveToDb(ByVal _detailsToSave as IMyInheritedInterface)As String。当我使用接口访问属性然后将它们链接到其余代码以传递给Db时,这是当我发现我看不到Abstract属性时,但是当我更改为实际类时,并且不使用界面,我可以看到一切。这是我的问题。 – Andy5

+1

而你在C#中也会遇到这个问题。如果你可以访问没有被界面暴露的成员,那么界面的重点是什么?如果'CommonString'是所有'MyInterface'类应该实现的东西,那么将它添加到接口中。 –

+0

是的 - 我开始看到这个! – Andy5