2012-07-12 70 views
2

我是C#新手,正在嘗試實現一個接口。我知道我不能將訪問修飾符放到接口方法中,因此我如何在下面的'TestClass2'的公共靜態'Create'方法中訪問'TestValue'?我得到的是錯誤...訪問其他類中實現的接口方法

「TestClass1」不包含可以發現

public interface IParent 
{ 
    string TestValue { get; } 
} 

public class TestClass1 : IParent 
{ 
    string IParent.TestValue 
    { 
     get { return "hello"; } 
    } 
} 

public class TestClass2 
{ 
    private string _testValue; 

    public static TestClass2 Create(TestClass1 input) 
    { 
     TestClass2 output = new TestClass2(); 
     output._testValue = input.TestValue; 
     return output; 
    } 
} 
爲「測試值」,並沒有擴展方法「測試值」接受型「TestClass1」的第一個參數的定義
+0

你只是不能把修飾符放在_description_上,但是你可以在_implementation_上使用它們。 – phg 2012-07-12 13:00:27

+0

不確定這裏的示例是否簡化了,但是您的靜態方法可以接受類型爲「IParent」而不是「TestClass1」的參數。這也會無意中修復你的錯誤(我希望有人會在下面的答案中解釋爲什麼)。 – 2012-07-12 13:01:37

+0

只是出於好奇(請不要指責我!) - 這條線是幹什麼的? private TestClass1 _testValue; 我也是一個小菜鳥,它看起來像它是在自己內部宣佈自己的一個實例嗎?再次,只是好奇,它可能是我將來可以使用的東西=) – Losbear 2012-07-12 13:01:47

回答

6

添加public訪問修飾符在具體實施

public class TestClass1 : IParent 
{ 
    private TestClass1 _testValue; 

    public string TestValue 
    { 
     get { return "hello"; } 
    } 
} 

編輯:你真地寫過一個顯式接口實現,我建議您看到以下SO問題:C# Interfaces. Implicit implementation versus Explicit implementation

+0

起初,我不能讓這個工作,但我忘了添加公共訪問修飾符。它現在很好用。謝謝你的幫助! – Thundter 2012-07-28 12:15:34

0

在接口聲明中不需要訪問修飾符,因爲接口的要點是爲實現接口的任何類定義可公開訪問的合約。實質上,雖然您沒有在定義中指定訪問修飾符,但所有方法/屬性都是公開的。

這意味着,當你實現接口,你合約約束提供該接口的方法/屬性的簽名相匹配的公共方法/屬性。

簡而言之,將public訪問修飾符添加到您的具體類實現中,您會很甜。

0

我試過對象轉換爲界面得到像這樣

public class TestClass2 
{ 
    private string _testValue; 

    public static TestClass2 Create(TestClass1 input) 
    { 
     TestClass2 output = new TestClass2(); 
     output._testValue = ((ITestInterface)input).TestValue; 
     return output; 
    } 
} 

這工作太解決方案,但我更喜歡簡單的解決方案。

相關問題