C#:哪些数据类型需要 NEW 来分配内存?
我想更好地理解使用“new”为变量分配内存和不需要 new 的情况之间的区别。
当我声明
int i; // I don't need to use new.
But
List<string> l = new List<string>();
说“new int()”有意义吗?
I want to understand better the difference between using 'new' to allocate memory for variables and the cases when new is not required.
When I declare
int i; // I don't need to use new.
But
List<string> l = new List<string>();
Does it make sense to say "new int()" ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
只需检查 IL:您可以看到编译器发出“initobj”或“newobj”。
initi = 0 时会发出 initobj;和 int i = new int();
http:// msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.initobj(v=vs.85).aspx
Simply check the IL: you can see the compiler emits either an 'initobj' or 'newobj'.
The initobj is emitted for both int i = 0; and int i = new int();
http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.initobj(v=vs.85).aspx
引用类型必须使用
new
进行分配。值类型不必在堆上分配。 Integer、Double 和 struct 类型是值类型的示例。局部变量的值类型将存储在函数调用堆栈上。作为类字段的值类型将存储在类的实例数据中。
Reference types must be allocated using
new
.Value types do not have to be heap allocated. Integer, Double, and struct types are examples of value types. A value type that is a local var will be stored on the function call stack. A value type that is a field of a class will be stored in the class's instance data.
int i
是 值类型 这就是为什么你不需要初始化并且new List()
是 引用类型,您需要为其分配一个对象实例int i
is value type that's why you don't need to initialize andnew List<string>()
is reference type, you need to assign an object instance to it请参阅有关新的 MSDN 文档
Have look to this MSDN documentation on new
您不需要在 C# 中添加新的值类型。您所做的所有其他类型。
You do not need to new value types in c#. All other types you do.
任何引用类型(例如类)都需要 new。值类型(例如 int)是简单值,不需要 new。
Any reference type (such as classes) will require new. Value types (such as int) are simple values and do not require new.
您将需要使用 new 来分配任何引用类型(类)。
任何值类型(例如 int 或 structs)都可以在不使用 new 的情况下声明。但是,您仍然可以使用新的。以下内容是有效的:
请注意,在初始化值类型之前,您无法直接访问该值类型。对于结构体,使用 new TheStructType() 通常很有价值,因为它允许您充分利用结构体成员,而无需首先显式初始化每个成员。这是因为构造函数执行初始化。对于值类型,默认构造函数总是将所有值初始化为 0。
new 与非默认构造函数一起使用,例如:
此外,对于结构体,您可以将
初始化结构体内部的值。话虽如此,这里不是必需的,只是一个选项。
You will need to use new to allocate any reference type (class).
Any value type (such as int or structs) can be declared without new. However, you can still use new. The following is valid:
Note that you can't directly access a value type until it's been initialized. With a struct, using
new TheStructType()
is often valuable, as it allows you full use of the struct members without having to explicitly initialize each member first. This is because the constructor does the initialization. With a value type, the default constructor always initializes all values to the equivalent of 0.Also, with a struct, you can use
new
with a non-default constructor, such as:This provides a way to initialize values inside of the struct. That being said, it is not required here, only an option.