C# —— 构造函数

什么是构造函数

构造函数: 一般在函数为类的属性初始值的作用,构造函数的名称类名

在类里面定义构造函数 方法名和类名同名 不能带返回值类型 void/非void 不能有

// 创建一个构造函数

cs 复制代码
class People
{
    public string Name { get; set; }
    public int Age { get; set; }
    private bool isChengNian;

    // 在类里面定义构造函数 方法名和类名同名 不能带返回值类型 void/非void 不能有
    // 构造函数
    public People()
    {
        Console.WriteLine(this.Name+Age+isChengNian);
    }

}
cs 复制代码
class HaiZei
{
    public string Name;
    public string Skill;
    public int Age;

    // 构造函数带参数
    public HaiZei(string name,string skill, int age)
    {
        // 把参数赋值给属性
        Name = name;
        Skill = skill;
        Age = age;
        Console.WriteLine(Name + Skill + Age );
    }
}


class Aircraft
{
    public string Sign { get; set; }
    public string Model { get; set; }
    public string Colour { get; set; }
    public string Subjection { get; set; }
    public double Speed { get; set; }
    public int AllCount { get; set; }
    public string Type { get; set; }
    public int Count { get; set; }
    public Aircraft(string name,string model,string colour,string subjection,double sp,int all)
    {
        Sign = name;
        Model = model;
        Colour = colour;
        Subjection = subjection;
        Speed = sp;
        AllCount = all;
        if (all  >= 400)
        {
            Type = "大";
        }
        else if (all >= 200 )
        {
            Type = "中";
        }
        else
        {
            Type = "小";
        }
        Random r = new Random();
        Count = r.Next(AllCount + 1);
    }

创建People 对象 构造函数已经调用,虽然在此处给这个属性赋值了,但是这个构造函数里面 并没有把这个初始值赋值给属性,在构造函数里面舒勇属性的时候 值为默认值

cs 复制代码
 ArrayList a1 = new ArrayList();
 ArrayList a2 = new ArrayList(100);
 People p1 = new People() { Name = "张三",Age=10};
 Console.WriteLine(p1.Name);

2为了解决在构造函数里面能够使用已经赋值过得属性,需要添加带参数的构造函数,通过参数传递给属性,

创建海贼对象 调用构造函数的时候把参数赋值给属性

cs 复制代码
    HaiZei lufei = new HaiZei("王路飞", "五档", 20) { Name="索隆",Skill="阿修罗",Age=20};

    HaiZei jide = new HaiZei("基德", "磨磁人", 20);

    Aircraft f1 = new Aircraft("波音", "747", "黄色", "南方航空", 100, 400);
    Console.WriteLine(f1.Type + f1.Count);

    Console.ReadLine();
}
相关推荐
虾球xz12 分钟前
CppCon 2018 学习:EFFECTIVE REPLACEMENT OF DYNAMIC POLYMORPHISM WITH std::variant
开发语言·c++·学习
Allen_LVyingbo16 分钟前
Python常用医疗AI库以及案例解析(2025年版、上)
开发语言·人工智能·python·学习·健康医疗
小哈龙21 分钟前
裸仓库 + Git Bash 搭建 本地 Git 服务端与客户端
开发语言·git·bash
唐青枫27 分钟前
C#.NET log4net 详解
c#·.net
G探险者40 分钟前
《如何在 Spring 中实现 MQ 消息的自动重连:监听与发送双通道策略》
java·开发语言·rpc
weixin_437398211 小时前
转Go学习笔记
linux·服务器·开发语言·后端·架构·golang
StrongerIrene2 小时前
rs build 的process.env的值undefined解决方案
开发语言·javascript·ecmascript
风逸hhh2 小时前
python打卡day58@浙大疏锦行
开发语言·python
让我们一起加油好吗2 小时前
【C++】list 简介与模拟实现(详解)
开发语言·c++·visualstudio·stl·list
Q_970956392 小时前
java+vue+SpringBoo足球社区管理系统(程序+数据库+报告+部署教程+答辩指导)
java·开发语言·数据库