gpt4 book ai didi

c# - 有没有更好的方法来解释 .net 中结构和类之间的行为差​​异?

转载 作者:行者123 更新时间:2023-11-30 20:14:45 24 4
gpt4 key购买 nike

下面的代码显示了我最近用来向开发新手解释结构和类的不同行为的示例。有更好的方法吗? (是的 - 代码使用公共(public)字段 - 这纯粹是为了简洁)

namespace StructsVsClasses
{
class Program
{
static void Main(string[] args)
{
sampleStruct struct1 = new sampleStruct();
struct1.IntegerValue = 3;
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);

sampleStruct struct2 = struct1;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
struct1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);

sampleClass class1 = new sampleClass();
class1.IntegerValue = 3;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);

sampleClass class2 = class1;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
class1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);

Console.ReadKey();
}
}

struct sampleStruct
{
public int IntegerValue;
}

class sampleClass
{
public int IntegerValue;
}
}

最佳答案

好吧,您的解释根本不是解释,而是对行为的观察,这是不同的。

如果您想要解释差异是什么,那么您需要一段文字解释。解释的行为可以用代码编辑。

Grimtron 链接到的页面非常适合详细说明类和结构之间的所有个体差异,其中的一些片段可以用作概述,特别是阅读以下项目:

  • 存在于栈上还是堆上?
  • 继承差异?

但我不会链接到该页面作为对差异的解释。这就像试图描述汽车是什么,然后列出构成汽车的所有零件一样。您仍然需要了解大局才能了解汽车是什么,而这样的列表无法为您提供。

在我看来,解释就是告诉您某事是如何工作的,然后所有细节自然而然地从中得出。

例如,如果您了解值类型与引用类型背后的基本原理,那么该页面上的很多细节都是有意义的,如果您仔细想想

例如,值类型(结构)在声明的地方分配,可以说是内联的。它占用堆栈空间,或者使类在内存中变大。然而,引用类型是一个指针,它具有固定大小,指向内存中存储实际对象的其他地方

有了上面的解释,下面的细节就说得通了:

  • 结构变量不能为空(即它总是占用必要的空间)
  • 对象引用可以为空(即指针可以不指向任何内容)
  • 结构不会增加垃圾收集的压力(垃圾收集与堆一起工作,堆是对象位于其他地方空间的地方)
  • 总是有一个默认的构造函数。由于您可以声明任何值类型变量(基本上是一种结构),而无需为其赋值,因此必须有一些潜在的魔法来清理该空间(记住我说过它无论如何都会占用空间)

其他的东西,比如所有与继承有关的东西,都需要在解释中有自己的一部分。

等等……

关于c# - 有没有更好的方法来解释 .net 中结构和类之间的行为差​​异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/100824/

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