gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:15 25 4
gpt4 key购买 nike

为什么它会返回 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 产生任何影响。

有关此主题的更多信息:

关于c# - 以下代码的输出 : Why would it return rainyday[1] = Sunday and not friday?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29138125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com