繁体   English   中英

For 循环或 out 中的声明变量有什么不同?

[英]What the different about the declaring variable in For loop or out?

  1. 为什么方法 Calcu1 与 ILSpy 中的方法 Calcu2 具有相同的代码,而其他方法则没有?

  2. 虽然它们是不同的类型(其中一些是引用类型,另一些是值类型),但为什么方法 Calcu3 是唯一具有不同哈希码的方法? 其他人是否声明和操作相同的变量?

     class Program { static void Main(string[] args) { Calcu8(); } static void Calcu1() { int single; for (int i = 0; i < 10; i++) { single = 5; Console.WriteLine(single + i); } } //Method Calcu2 has the same code as Method Calcu1 in ILSpy static void Calcu2() { for (int i = 0; i < 10; i++) { int single = 5; Console.WriteLine(single + i); } } //class type static void Calcu3() { for (int i = 0; i < 10; i++) { Student stu = new Student(); stu.Name = "Tim"; //not the same Console.WriteLine(stu.GetHashCode()); } } //class type static void Calcu4() { Student stu = new Student(); for (int i = 0; i < 10; i++) { stu.Name = "Tim"; //same Console.WriteLine(stu.GetHashCode()); } } //string static void Calcu5() { string str = string.Empty; for (int i = 0; i < 10; i++) { str = "Hello"; //same Console.WriteLine(str.GetHashCode()); } } //string static void Calcu6() { for (int i = 0; i < 10; i++) { string str = string.Empty; str = "Hello"; //same Console.WriteLine(str.GetHashCode()); } } //struct static void Calcu7() { Person per = new Person(); for (int i = 0; i < 10; i++) { per.Name = "Tim"; //same Console.WriteLine(per.GetHashCode()); } } //struct static void Calcu8() { for (int i = 0; i < 10; i++) { Person per = new Person { Name = "Tim" }; //same Console.WriteLine(per.GetHashCode()); } }

    }

    公共 class 学生 { 公共字符串名称; }

    公共结构人{公共字符串名称; }

首先,让我指出您的方法之间的区别:

方法Calcu1Calcu4Calcu5Calcu7 :该变量已在外部声明并在循环内部设置。 该值将出现在循环之外。

方法Calcu2Calcu3Calcu6Calcu8 :该变量已在循环内部声明,并且在外部不可用。

您的Calcu3的 hashCode 发生变化,因为您每次都创建不同的 object。 通过 new 创建一个Student ,堆栈将引用堆上的新 object。 此引用每次都在更改,因为您正在创建 10 个新对象。

你的Calcu8的 hashCode 不一样,因为它是一个struct ,结构体保存在堆上。

有关堆栈堆的更多信息,请参见此处 在这方面,您还可以找到堆上和堆栈上的定义。

在堆栈上:

使用以下类型声明列表声明的“事物”是值类型(因为它们来自 System.ValueType):bool、byte、char、decimal、double、enum、float、int、long、sbyte、short、 struct 、uint、 ulong, ushort

在堆上:

"Things" declared with following list of type declarations are Reference Types (and inherit from System.Object... except, of course, for object which is the System.Object object): class, interface, delegate, object, string

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM