Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# interface

作者:冷视天下   发布日期:2026-07-01   浏览:29

// 定义一个接口 IAnimal,包含一个方法 MakeSound
public interface IAnimal
{
    void MakeSound();
}

// 实现接口的类 Dog
public class Dog : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("汪汪");
    }
}

// 实现接口的类 Cat
public class Cat : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("喵喵");
    }
}

// 使用接口
public class Program
{
    public static void Main()
    {
        // 创建接口类型的变量,并实例化为 Dog 和 Cat
        IAnimal myDog = new Dog();
        IAnimal myCat = new Cat();

        // 调用接口方法
        myDog.MakeSound();  // 输出: 汪汪
        myCat.MakeSound();  // 输出: 喵喵
    }
}

解释说明:

  • 接口 (Interface):接口定义了一组行为(方法、属性、事件等),但不提供具体实现。任何实现了该接口的类都必须提供这些行为的具体实现。
  • IAnimal 接口:这里定义了一个 IAnimal 接口,其中包含一个 MakeSound 方法,所有实现该接口的类都必须实现这个方法。
  • Dog 和 Cat 类:这两个类分别实现了 IAnimal 接口,并提供了 MakeSound 方法的具体实现。
  • Main 方法:在 Main 方法中,我们创建了 DogCat 的实例,并通过接口类型调用了 MakeSound 方法。

上一篇:c# list 去重

下一篇:c# urlencode

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站