`
wsql
  • 浏览: 11788142 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

C#带参数的构造函数

 
阅读更多

构造函数可以没有参数,也可以包含一个以上的参数,带参数的构造函数用于初始化成员变量,在实例化类时完成初始化的过程。其语法如下:

class 类名
{
<访问修饰符> 类名 (参数列表)
{
//构造函数主体
}
}

访问带参数的构造函数如下:

类名 对象名=new 类名(参数值);

using System;
class Dog
{
public string type;
public string color;
public Dog(string strtype, string strcolor)
{
this.type = strtype;
this.color = strcolor;
}

}

class Program
{
static void Main()
{
Dog mydog = new Dog("我的狗", "花色");
Console.WriteLine("我的狗品种为{0},颜色为{1}", mydog.type,

mydog.color);
Console.ReadLine();
}
}

带参数的构造函数,要求其参数的数据类型必须与成员变量的数据类型相同,可以是一个参数,也可是多个参数。

注意:如果在类中只声明了带参数的构造函数,那么创建对象时,必须有相同数据类型和相同数量的参数值传递。否则会出现编译错误。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics