2011-12-19 116 views
-1

我有以下類:如何從基類派生並在C#中實現接口?

public class ContentService : IContentService 

我想作一個BaseService類並實現一些常見的功能在那裏。不過,我也想實現所有的IContentService方法。

我該如何修改這一行,使它既實現接口又從BaseService繼承?

回答

1

您可以從基類和接口繼承您的類。在基類中實現接口爲您提供了不實現所有接口方法的選項。如下例:

interface ITestInterface 
{ 
    void Test(); 
    string Test2(); 
} 

public class TestBase : ITestInterface 
{ 
    #region ITestInterface Members 

    public void Test() 
    { 
     System.Console.WriteLine("Feed"); 
    } 

    public string Test2() 
    { 
     return "Feed"; 
    } 

    #endregion 
} 

public class TestChild : TestBAse, ITestInterface 
{ 
    public void Test() 
    { 
     System.Console.WriteLine("Feed1"); 
    } 
} 

public static void Main(){ 
    TestChild f = new TestChild(); 
    f.Test(); 

    var i = f as ITestInterface; 

    i.Test(); 
    i.Test2();//not implemented in child but called from base. 
} 
4
public class ContentService: BaseService, IContentService 
{ 
} 

您可以根據需要添加儘可能多的接口,並且最多可以添加一個基類到列表中。只需使用逗號分隔每個額外的界面。

基類不需要是列表中的第一個項目。

1

public class ContentService: BaseService, IContentService

將從BaseService繼承和實現IContentService接口。

您可能還想查詢基類的抽象類/方法。

相關問題