C#在无参构造器中初始化成员变量
作者:网络转载 发布时间:[ 2013/12/30 16:36:18 ] 推荐标签:C# 变量
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/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11