2012-10-03 24 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