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

标签 c# arrays value-type reference-type

为什么它会返回 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/

相关文章:

c# - 将 Observable 集合写入 Csv 文件

c# - ShowDialog 退出时如何防止焦点改变?

php - 如何从数组中去除只有空白的元素?

c# - 结构包装器类型的默认相等性比较 C#

c# - 可与 switch() 一起使用的自定义结构/类型

c# - 在ctor中带参数的Windsor依赖注入(inject)

c# - 用户控件的可见属性何时会影响其子项?

c++ - 引用 const char* 数组

javascript - 从数组中删除最后一项(并且不返回项)

C# 在缓存中存储值类型