在C#中,接口(interface)是一个定义了一组方法和属性但不包含实现的类型。接口为实现这些成员的类或结构提供了一种契约。使用接口可以实现多重继承,因为一个类可以实现多个接口。
接口的定义
定义一个接口使用interface
关键字,接口中的方法和属性没有实现,只定义它们的签名:
namespace 接口练习
{
internal interface IExample
{
void Method1();
int Method2(string param);
string MyProperty { get; set; }
}
}
实现接口
一个类或结构实现接口时,必须实现接口中的所有成员:
public class Example : IExample
{
public string MyProperty
{ get; set;}
public void Method1()
{
Console.WriteLine("Method1 implementation");
}
public int Method2(string param)
{
Console.WriteLine($"Method2 implementation with parameter: {param}");
return param.Length;
}
}
接口的使用
实现接口的类实例化后,可以通过接口类型的变量来访问其方法和属性:
static void Main(string[] args)
{
IExample example = new Example();
example.Method1();
int v = example.Method2("helloworld");
Console.WriteLine(v);//返回字符串长度
Console.ReadLine();
}
接口的继承
接口可以继承其他接口,这使得接口可以扩展另一个接口的成员。
public interface IBase
{
void BaseMethod();
}
public interface IDerived : IBase
{
void DerivedMethod();
}
public class DerivedClass : IDerived
{
public void BaseMethod()
{
Console.WriteLine("BaseMethod implementation");
}
public void DerivedMethod()
{
Console.WriteLine("DerivedMethod implementation");
}
}
接口的实际应用
接口在C#中有多种实际应用,以下是一些常见的场景:
- 多态性:接口允许不同类以相同的方式被处理。例如,多个类实现相同的接口可以在同一个集合中进行处理。
- 解耦:接口可以用于解耦类之间的依赖关系,使得代码更加灵活和可测试。
- 依赖注入:在依赖注入中,接口经常用于定义依赖项,使得可以轻松替换具体实现。