[英]How can I derive from a base class and implement an interface in C#?
我有以下課程:
public class ContentService : IContentService
我想制作一個BaseService類,並在那里實現一些常用功能。 但是,我還想實現所有IContentService方法。
如何修改此行,使其既實現接口又繼承自BaseService?
public class ContentService: BaseService, IContentService
{
}
您可以根據需要添加任意數量的接口,並且列表中最多可以添加一個基類。 只需使用逗號分隔每個其他接口。
同樣,基類也不必成為列表中的第一項。
public class ContentService: BaseService, IContentService
將繼承自BaseService並實現您的IContentService接口。
您可能還想為基類查找Abstract類/方法。
您可以從基類和接口繼承您的類。 在基類中實現接口為您提供了不實現所有接口方法的選項。 像下面的例子:
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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.