C#封装之初始化对象和方法参数

用对象初始化器初始化对象

   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=3Growth(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); 这是错误的//在实参调用的时候不能定义变量,不能定义变量!!!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值