2014-04-01 65 views
1

說我有實現它是否需要實例化一個類以供您閱讀其屬性之一?

public class concrete1 : IType{ 

    public string property1 {get {return "testing1";}} 
} 
public class concrete2 : IType{ 

    public string property1 {get {return "testing2";}} 
} 

我可以找出是哪個類包含字符串「testing2」沒有實例或者類的接口

public interface IType{ 
    string property1 {get;} 
} 

和兩個班?這樣我才能實例化只有特定的一個。

+7

我沒有蘋果。蘋果是紅色的嗎?也許,如果它是一個靜態蘋果。 – Magus

+0

大聲笑,這就是我的想法,但很好奇,如果有人知道任何魔術 – erotavlas

+2

這聽起來像有可能是一種更簡單的方法來實現您的最終目標。這可能是重新審視你的設計的時候了。你真的想要解決什麼問題?我的大腦現在正尖叫着「工廠模式」,但您並沒有真正提供足夠的信息來確定。 – itsme86

回答

4

是的,它的確如此。

一個對象只包含實例化的數據。即使你像上面那樣定義一個屬性,你仍然需要實例化它。但是,如果你創建一個靜態屬性,你將可以通過調用concrete1.property1等來訪問它。

但我不相信你可以根據接口定義一個靜態屬性。

2

不,你不能引用沒有類的實例的實例成員(比如那個屬性)。您將需要使該屬性static無需實例即可獲取。

相關問題