C#在无参构造器中初始化成员变量

发表于:2013-12-30 10:13

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:cuijianzhongswust    来源:51Testing软件测试网采编

using System;
#region
/*
/// <summary>
/// 类定义
/// </summary>
class Person
{
//成员变量
int name;
int height;
//成员方法
void eat()
{
}
}
class Test
{
static void Main()
{
Person baby = new Person();     //对象
baby.name =
Person YaoMin = new Person();   //对象
}
}
*/
#endregion
class A
{
//1.如果直接在这里初始化,那么每一个构造函数在编译的时候都会有相应的初始化代码
public int i = 100;
public string s = "stone";
public A()
{
Console.WriteLine("constructor");
}
//2.如果成员变量在无参构造函数中初始化,然后在有参构造函数中调用无参构造函数,这样有参构造函数中就不会重复初始化成员变量了
public int i;
public string s;
public A()
{
Console.WriteLine("constructor");
i = 100;
s = "stone";
}
public A(int i):this()
{
this.i = i;
}
public A(string s):this()
{
this.s = s;
}
public A(int i, string s):this()
{
this.i = i;
this.s = s;
}
}
class Test
{
static void Main()
{
//A a = new A();
//Console.WriteLine("i="+a.i);
//Console.WriteLine("s="+a.s);
A a = new A();
Console.WriteLine("first constructor");
Console.WriteLine(a.i);
Console.WriteLine(a.s);
Console.WriteLine();
A a1 = new A(1);
Console.WriteLine("second constructor");
Console.WriteLine(a1.i);
Console.WriteLine(a1.s);
Console.WriteLine();
A a2 = new A("I am third constructor");
Console.WriteLine("third constructor");
Console.WriteLine(a2.i);
Console.WriteLine(a2.s);
Console.WriteLine();
A a3 = new A(3, "I am the forth constructor");
Console.WriteLine("Forth constructor");
Console.WriteLine(a3.i);
Console.WriteLine(a3.s);
}
}
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号