用对象初始化器初始化对象
Child child2 = new Child() { Name = "肖战", Age = 7 };
Console.Write("我叫" + child2 .Name);
Console.Write(",今年" + child2.Age + "岁");
方法中的参数
静态输入
main{
Child stu = new Child("小明",Gender.女,5);
Growth(stu);//调用静态方法
Growth(stu.Age);
Console.WriteLine("我现在{0}岁了",stu.Age);
}
static void Growth(Child child)//传递的是地址
{
child.Age++;
Console.Write("1哦,我有长了一岁");
//输出age的结构为6
}
static void Growth(int age)
{
age++;
Console.Write("2哦,我有长了一岁");
//输出age的结构为5
}
1:引用类型参数:按引用传参,储存的是地址。
方法修改形参,通常实参也被修改
2:值类型参数,按值传参
方法修改形参,实参不会改变。
ref关键字
//ref 关键字 方法参数变成引用传递(地址),形参和实参是一个参数
main{
int age=3;
Growth(ref age); //实参调用的时候加入关键字ref
Console.WriteLine("age in main is:{0}", age);
}
static void Growth(ref int age)
{
age++;
Console.WriteLine("age in method growth is:{0}", age);
}
//输出为“age in main is:4” “age in method growth is:4”
1:可以让值类型参数变成按引用参数,需要在数前面加ref
2: 对象属性(创建对象)不能作为实参,例“ Growth(ref age);”
out关键字
main{
int a, b;
Growth(age,out a,out b);
Console.WriteLine("我去年{0}岁了,今年{1}岁了", a, b);
}
static void Growth(int age,out int lastyear,out int nextyear)
{
lastyear = age - 1;
nextyear = age + 1;
}
1:ref的作用是传参数,而out的作用是获取结果。
2:return只能返回一个值,而out可以返回多个值
默认参数
1:默认参数不传参数
int age = 3;
Growth1();//默认参数
Console.WriteLine("age in main is:{0}", age);
static void Growth1(int age=5)
{
age++;
Console.WriteLine("age in method growth is:{0}",age);
}
//输出为age in main is:6;age in method growth is 6
2:默认参数直接传参数
int age = 3;
Growth1(8);//默认参数
Console.WriteLine("age in main is:{0}", age);
static void Growth1(int age=5)
{
age++;
Console.WriteLine("age in method growth is:{0}",age);
}
//输出为age in main is:8;age in method growth is 8
3:默认参数传二个参数
int age = 3;
Growth1(age,8);//默认参数,参数必须在有值的数前面
Console.WriteLine("age in main is:{0} ", age);
static void Growth1(int a,int age=5)
{
a=5;
age++;
Console.WriteLine("age in method growth is:{0} {1}", a,age);
}
//输出:age in main is:5;age in method growth is:5 9
注意:Growth( int age=4); 这是错误的//在实参调用的时候不能定义变量,不能定义变量!!!