【发布时间】:2020-08-15 13:57:36
【问题描述】:
-
为什么方法 Calcu1 与 ILSpy 中的方法 Calcu2 具有相同的代码,而其他方法则没有?
-
虽然它们是不同的类型(其中一些是引用类型,另一些是值类型),为什么方法Calcu3是唯一具有不同hashcode的方法?其他人声明和操作的是同一个变量吗?
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()); } }}
公开课学生{ 公共字符串名称; }
公共结构人{ 公共字符串名称; }
【问题讨论】:
-
因为值类型的代码正在被优化,但引用类型的代码却不能,它与
new Student()的实例化一次和在循环体中的工作方式不同。因此,1 个实例与 10 个实例之间存在差异。struct不是 by-ref 类型,它在此处的行为类似于int。
标签: c#