為什么運行結果是4歲,5歲,4歲????
? ? ? ? ? ? Child child = new Child("劉小明", 3, Gender.女);
? ? ? ? ? ? int age = 3;
? ? ? ? ? ? Growth(child);//直接調用靜態方法,類是引用類型,修改形參,實參child也被修改
? ? ? ? ? ? Growth(child.Age);//int是值類型,修改形參,實參未改變-----》??????但是為什么運行結果和視頻中的不一樣,我的改變了
? ? ? ? ? ? //Growth(ref age);
? ? ? ? }
? ? ? ? static void Growth(Child c)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? c.Age++;
? ? ? ? ? ? ? ? Console.WriteLine("我是A方法,我今年{0}歲了",c.Age);
? ? ? ? ? ? }
? ? ? ? ? static void Growth(int age)
? ? ? ? ? ? {
? ? ? ? ? ? ? ?age++;
? ? ? ? ? ? ? ? Console.WriteLine("我是B方法,我今年{0}歲了", age);
? ? ? ? ? ? }
? ? ? ? static void Growth(ref int age)//???為什么跟視頻中的相反,ref不是能使值類型按照引用類型傳參,為什么顛倒了
? ? ? ? {
? ? ? ? ? ? age++;
? ? ? ? ? ? Console.WriteLine("我是C方法,我今年{0}歲了", age);
? ? ? ? }
2019-03-11
題主好像對方法理解有點錯誤啊,第二步,你的輸出語句在方法里面,當你傳的值是4,++之后肯定會變成5,這個時候輸出肯定是5啦
視頻的輸出都是寫在方法調用之后,而不是方法體里面
2019-01-05
代碼第二步?Growth(child.Age);視頻中一樣的方法輸出卻是4歲,說傳入的int類型是值類型,也就是復制副本,實際參數并未改變。
2019-01-03
代碼第一步?Growth(child); 此時child.Age為new Child("劉小明", 3, Gender.女);中所賦值的3。在static void Growth(Child c)中運行? ??c.Age++;為4歲。
代碼第二步?Growth(child.Age); 此時傳遞為第一步中運行后的結果4? 所以傳入方法中的參數就是4。在?static void Growth(int age) 中運行?age++; 為5。
代碼第三步 Growth(ref age);傳遞的值 為?int age = 3;? 因此?static void Growth(ref int age)中??age++;結果為4。