Skip to main content
 首页 » 编程设计

c#之以下代码的输出 : Why would it return rainyday[1] = Sunday and not friday

2024年02月06日16yxwkf

为什么它会返回 rainyday[1] = Sunday 而不是星期五?并在其他地方返回 main() 中定义的所有值

  Namespace ConsoleApp_toTestYourself 
    { 
        public struct forecast 
        { 
            public int temp { get; set; } 
            public int press { get; set; } 
        } 
 
 
        class structStaticTest 
        { 
            public static void cts(string weather) { weather = "sunny"; } 
            public static void cta(string[] rainyDays) { rainyDays[1] = "Sunday"; } 
            public static void ctsr(forecast f) { f.temp = 35; } 
 
            static void Main(string[] args) 
            { 
                string weather = "rainy"; 
                cts(weather);   //calling static method 
                Console.WriteLine("the weather is " + weather); 
 
                string[] rainyDays=new[]{"monday","friday"}; 
                    cta(rainyDays);  calling static method 
                Console.WriteLine("the rain days were on "+rainyDays[0]+"  and   "+ rainyDays[1]); 
 
                forecast f = new forecast { press = 700, temp = 20 }; 
                ctsr(f);  //calling static method 
                Console.WriteLine("the temperature is  " + f.temp + "degree celcius"); 
                Console.ReadLine(); 
            } 
        } 
    } 

它的输出是: 雨天 星期一星期天 20摄氏度

请您参考如下方法:

因为 cta 方法将 rainyDays[1] 设置为星期日:

public static void cta(string[] rainyDays) { rainyDays[1] = "Sunday"; } 

它在写入控制台之前被调用:

cta(rainyDays);  //calling static method 
Console.WriteLine("the rain days were on "+rainyDays[0]+"  and   "+ rainyDays[1]); 

编辑:关于静态方法之间的差异。其他方法不会更改传递的对象。

首先,cts 不会改变字符串对象:

weather = "sunny"; 

不会改变原始对象。它创建新的字符串对象 "sunny" 并将其分配给一个变量(方法参数)。

有关此主题的更多信息:

其次,ctsr 接受结构 forecast 作为参数。结构按值传递,方法接收原始结构的副本并对其进行操作。因此,您的更改不会对 main 方法中的 weather 产生任何影响。

有关此主题的更多信息: