為什么我這個輸出的是:我今年1歲了和我今年2歲了?
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Youeryuan
{
? ? class Program
? ? {
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? Child c1 = new Child("曉強(qiáng)", 3);
? ? ? ? ? ? Growth(c1);
? ? ? ? ? ? Growth(c1.Age);
? ? ? ? ? ? Console.ReadLine(); ? ? ? ? ??
? ? ? ? }
? ? ? ?
? ? ? ? static void Growth(Child chlid)
? ? ? ? {
? ? ? ? ? ? chlid.Age++;
? ? ? ? ? ? Console.WriteLine("我今年"+chlid.Age+"歲了1!");
? ? ? ? ? ?// Console.WriteLine("我又長大了一歲!");
? ? ? ? ? ??
? ? ? ? }
? ? ? ? static void Growth (int age)
? ? ? ? {
? ? ? ? ? ? age++;
? ? ? ? ? ? Console.WriteLine("我今年{0}歲了2!", age);
? ? ? ? }
? ? ? ?
? ? }
}
2021-03-04
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ceshi1
{
? ? class Program
? ? {
? ? ? ? class Child
? ? ? ? {
? ? ? ? ? ? private string name;
? ? ? ? ? ? public string Name
? ? ? ? ? ? {
? ? ? ? ? ? ? ? get { return name; }
? ? ? ? ? ? ? ? set { name = value; }
? ? ? ? ? ? }
? ? ? ? ? ? private int age;
? ? ? ? ? ? public int Age
? ? ? ? ? ? {
? ? ? ? ? ? ? ? get { return age; }
? ? ? ? ? ? ? ? set { age = value; }
? ? ? ? ? ? }
? ? ? ? ? ? public Child(string name, int age)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? this.name = name;
? ? ? ? ? ? ? ? this.age = age;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? Child c1 = new Child("曉強(qiáng)", 3);
? ? ? ? ? ? Growth(c1);
? ? ? ? ? ? Growth(c1.Age);
? ? ? ? ? ? Console.ReadLine();
? ? ? ? }
? ? ? ? static void Growth(Child chlid)
? ? ? ? {
? ? ? ? ? ? chlid.Age++;
? ? ? ? ? ? Console.WriteLine("我今年" + chlid.Age + "歲了1!");
? ? ? ? ? ? // Console.WriteLine("我又長大了一歲!");
? ? ? ? }
? ? ? ? static void Growth(int age)
? ? ? ? {
? ? ? ? ? ? age++;
? ? ? ? ? ? Console.WriteLine("我今年{0}歲了2!", age);
? ? ? ? }
? ? }
}
應(yīng)該是構(gòu)造方法沒有給age賦值的錯誤,main方法中實例化Child類對象c1時傳的參數(shù)3到構(gòu)造方法為age賦值的代碼錯誤,建議檢查構(gòu)造方法,如果沒有給age賦值,則默認(rèn)int型數(shù)據(jù)初始為0,也就會出現(xiàn)輸出為??
我今年1歲了!
我今年2歲了!
2020-04-04
你的Main方法和兩個Growth方法平級的,也就是說,程序開始時直接進(jìn)入 Growth(Child child) , Child.Age默認(rèn)取0,child.Age++ 后得1,這里輸出了“我今年1歲了1!”。接下來上面的 Growth(c1.Age) 讀取到的值為1,再傳到Growth(int age)中,age讀取到的值為1,age++ 得到2,故,這里輸出“我今年2歲了2!”?
望指點
2020-02-17
應(yīng)該是你的構(gòu)造方法中沒有給年齡Age初始化,導(dǎo)致c1對象Age取默認(rèn)值0
2019-09-06
? static void Growth (int age)
? ? ? ? {
? ? ? ? ? ? age++;
? ? ? ? ? ? Console.WriteLine("我今年{0}歲了2!", age);
? ? ? ? }
上面代碼你輸出的age是這個方法內(nèi)的值,在這個方法里age的初始值是零,你的代碼age++,輸出的結(jié)果自然就1啦
2019-07-18
首先你需要把兩個輸出語句中的child.Age和age都改成c1.Age,因為是輸出對象的年齡屬性必須用?對象.屬性?這種方式輸出.
其次你需要把兩條輸出語句放入主方法也就是Main函數(shù)內(nèi)部執(zhí)行,因為對象c1是在Main函數(shù)內(nèi)部實例化的。
最后加油加油加油