命名空间和类

using System;// 把System命名空间引用到程序中
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HW // 我们编写的Program类放在了HW命名空间中
{
    class Program // Class 在代码中是水蓝色
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello.World!"); // Console也是类,WriteLine是Console类中的一个方法;Program类是HW命名空间中的类,Console是System命名空间中的类,若不写using System;就无法用Console方法。
            Console.ReadLine();
        }
    }
}

若不写using System;则用下中方法也是可以的


namespace HW
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("Hello.World!");
            System.Console.ReadLine();// 但是如果这样用的话,每次用Console这个方法都需要写一遍System.
        }
    }
}
在 PHP 中,**命名空间(Namespace)** **的继承(Class Inheritance)** 是两个非常重要的面向对象编程特性。它们分别用于组织代码结构实现之间的继承关系。 下面我将详细解释这两个概念,并提供示例代码说明如何同时使用命名空间的继承。 --- ### 示例:PHP 命名空间的继承结合使用 ```php <?php // 定义命名空间 App\Models namespace App\Models; // 父 Animal 在 App\Models 命名空间下 class Animal { public function speak() { echo "Animal speaks.\n"; } } // 子 Dog 继承自 Animal,也在同一个命名空间中 class Dog extends Animal { public function speak() { echo "Dog barks.\n"; } } // 定义另一个命名空间 App\Controllers namespace App\Controllers; // 引入 App\Models 下的 Dog use App\Models\Dog; class AnimalController { public function handle() { $animal = new \App\Models\Animal(); // 使用全限定名称访问 Animal $dog = new Dog(); // 使用 use 导入后可以直接使用别名 $animal->speak(); // 输出: Animal speaks. $dog->speak(); // 输出: Dog barks. } } // 实例化控制器并调用方法 $controller = new AnimalController(); $controller->handle(); ``` --- ### 解释: 1. **命名空间的作用**: - `namespace App\Models;` 将 `Animal` `Dog` 两个归入 `App\Models` 命名空间。 - 这样即使多个重名,只要它们在不同的命名空间中就不会冲突。 - 命名空间也方便自动加载(Autoload),例如配合 Composer 使用 PSR-4 规范。 2. **的继承**: - `Dog` 继承了 `Animal` ,并重了 `speak()` 方法。 - 通过 `extends` 关键字可以建立父子关系,子可以复用父的方法属性,并可进行扩展或覆盖。 3. **use 的作用**: - `use App\Models\Dog;` 表示在当前命名空间 `App\Controllers` 中导入 `Dog` 。 - 这样可以在不重复完整命名空间的情况下使用该。 - 如果没有 `use`,则需要成 `\App\Models\Dog`。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值