如何用c#写一个接口,请举出实例
时间: 2024-03-06 10:47:26 浏览: 88
可以使用C#语言中的interface关键字来定义接口,以下是一个简单的例子:
```
interface IAnimal
{
void Eat();
void Sleep();
}
class Cat : IAnimal
{
public void Eat()
{
Console.WriteLine("Cat is eating...");
}
public void Sleep()
{
Console.WriteLine("Cat is sleeping...");
}
}
class Dog : IAnimal
{
public void Eat()
{
Console.WriteLine("Dog is eating...");
}
public void Sleep()
{
Console.WriteLine("Dog is sleeping...");
}
}
class Program
{
static void Main(string[] args)
{
IAnimal animal1 = new Cat();
animal1.Eat();
animal1.Sleep();
IAnimal animal2 = new Dog();
animal2.Eat();
animal2.Sleep();
Console.ReadLine();
}
}
```
在上述代码中,定义了一个IAnimal接口,包含了Eat()和Sleep()两个方法,分别代表动物的进食和睡眠行为。Cat和Dog类都实现了IAnimal接口,并重写了接口中的Eat()和Sleep()方法。最后在Main方法中创建了两个IAnimal类型的对象,分别是Cat和Dog,并调用它们的Eat()和Sleep()方法。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)