【问题标题】:Output of following code : Why would it return rainyday[1] = Sunday and not friday?以下代码的输出:为什么它会返回 rainyday[1] = Sunday 而不是 Friday?
【发布时间】:2015-03-23 18:54:12
【问题描述】:

为什么它会返回rainyday[1] = Sunday 而不是 Friday?和其他地方返回 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摄氏度

【问题讨论】:

  • 你改变了rainyDays[1] = "Sunday"的值

标签: c# arrays value-type reference-type


【解决方案1】:

因为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 接受 struct forecast 作为参数。结构是按值传递的,方法接收原始结构的副本并对其进行操作。因此,您的更改不会对 main 方法中的 weather 产生任何影响。

更多关于这个话题:

【讨论】:

    【解决方案2】:

    这是因为c#中引用类型和值类型之间的差异,结构是值类型,当您收到一个结构作为参数时,将创建一个不同的副本,因此如果您更改其中一个,另一个不会更改.变量 (f) 保存结构在堆栈上的实际数据,而不是引用类型,该变量只保存对堆上内存位置的引用(实际数据),指针本身在堆栈上。在rainyday[1] = Sunday的情况下,您更改了原始数据,因为没有副本并且您正在处理原始数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-15
      • 2021-10-28
      • 2022-06-27
      • 2020-02-14
      • 1970-01-01
      • 2023-02-12
      • 2020-03-14
      • 1970-01-01
      相关资源
      最近更新 更多