博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#构造函数的重载
阅读量:7057 次
发布时间:2019-06-28

本文共 1604 字,大约阅读时间需要 5 分钟。

C#中的构造函数也可以应用方法重载。C#中有默认构造函数,也可以定义带参数的构造函数。构造函数必须与类同名,并且不能有返回值。所以C#构造函数重载相当于不同数量的参数方法重载。

using System;

class Animal
{
public string _name;
public string _color;
public int _speed;
public Animal()
{
    this._speed = 30;
}
public Animal(string name, string color)
{
    this._name = name;
    this._color = color;
}
public Animal(string name, string color, int speed)
{
    this._name = name;
    this._color = color;
    this._speed = speed;
}
}

class Program

{
static void Main(string[]args)
{
    //方法一
    Animal animal1 = new Animal();
    animal1._name = "兔子";
    animal1._color = "灰色";
    //animal1._speed = 40;
    Console.WriteLine(
      "调用默认构造函数输出动物为{0},颜色为{1},奔跑速度为{2}km/h",

    animal1._name, animal1._color, animal1._speed);

    //方法二
    Animal animal2 = new Animal("狗", "黄色");
    Console.WriteLine("调用两个参数构造函数输出动物为{0},颜色为{1}",
      animal2._name, animal2._color);
    //方法三
    Animal animal3 = new Animal("花猫", "白色", 20);
    Console.WriteLine(
      "调用三个参数构造函数输出动物为{0},颜色为{1},奔跑速度为{2}",
      animal3._name, animal3._color, animal3._speed);
    Console.WriteLine("一只" + animal3._color + "的" + animal3._name + "正在以"
      + animal3._speed + "km/h的速度在奔跑\n");

    Console.ReadLine();

}

}

我们再看一个例子:

using System;

class Program
{
private string _name;
private int _age;
private string _qualification;
public Program()
{
    _age = 18;
}
public Program(string name, int age, string qualification)
{
    this._name = name;
    this._age = age;
    this._qualification = qualification;
}

static void Main()

{
    Program p = new Program();
    Console.WriteLine("默认构造函数输出年龄为" + p._age);
    Program p1 = new Program("李公", 19, "大学");
    Console.WriteLine("参数构造函数输出姓名为" + p1._name + ",年龄为" + p1._age
      + ",文化程度为" + p1._qualification);
}
}

转载地址:http://lfgol.baihongyu.com/

你可能感兴趣的文章
hdu 1232 畅通工程(并查集)
查看>>
在github上写个人简历——先弄个主页
查看>>
用jquery实现遮罩层
查看>>
POJ 2229 Sumsets(技巧题, 背包变形)
查看>>
啥时候js单元测试变的重要起来?
查看>>
使用strtotime和mktime时参数为0时返回1999-11-30的时间戳问题
查看>>
php mysql 扩展安装
查看>>
Thrift架构~目录
查看>>
c++ 调用matlab程序
查看>>
一个cocoapods问题的解决,希望能帮助到遇到相似情况的人
查看>>
AsyncHttpClient来完成网页源代码的显示功能,json数据在服务器端的读取还有安卓上的读取...
查看>>
Java线程池使用说明
查看>>
POSTGRESQL 创建表结构、修改字段、导入导出数据库(支持CSV)
查看>>
POJ训练计划2299_Ultra-QuickSort(归并排序求逆序数)
查看>>
PHP 语法
查看>>
LayoutInflater的使用
查看>>
修改用户进程可打开文件数限制(转)
查看>>
八大排序算法总结
查看>>
CodeForces Round #257 (Div. 2)
查看>>
【原】关于AdaBoost的一些再思考
查看>>