当operator new()与引用类型一起使用时,实例的空间在堆上分配,引用变量本身放在堆栈上.除此之外,在堆上分配的引用类型实例中的所有内容都将被清零.
例如,这是一个类:
class Person
{
public int id;
public string name;
}
Run Code Online (Sandbox Code Playgroud)
在以下代码中:
class PersonDemo
{
static void Main()
{
Person p = new Person();
Console.WriteLine("id: {0} name: {1}", p.id, p.name);
}
}
Run Code Online (Sandbox Code Playgroud)
p变量在堆栈上,并且Person(所有它的成员)的创建实例都在堆上.p.id会是0 和p.name将会null.这将是这种情况,因为堆上分配的所有内容都已清零.
现在我感到困惑的是,如果我使用带new运算符的值类型.例如,考虑以下结构:
struct Date
{
public int year;
public int month;
public int day;
}
class DateDemo
{
static void Main()
{
Date someDate;
someDate= new Date();
Console.WriteLine("someDate is: {0}/{1}/{2}",
someDate.month, …Run Code Online (Sandbox Code Playgroud) 如果我执行以下语句:
dim defaultDate as Date = Nothing
Run Code Online (Sandbox Code Playgroud)
defaultDate包含Date结构的默认值
我怀疑有一种干净的方式来检索这个值,就像某种buitin常数,但我无法找到它.
问:在VB.net中检索给定结构的默认值的干净方法是什么?
struct vvvv
{
public int j = 8;
//public vvvv() { } error
}
class cccc
{
public int f = 8;
}
Run Code Online (Sandbox Code Playgroud)
在结构中,如果我注释掉构造函数,编译器会告诉我,j在指定显式构造函数之前,该字段不会被初始化,而在类的情况下,初始化程序将在隐式构造函数的主体运行之前完美运行。
我的意思是该结构还有一个隐式构造函数。为什么我必须指定一个显式的初始化程序才能运行?隐式构造函数还不够吗?
可能重复:
C#中的结构与类
很抱歉,如果这是一个开放式问题,但我只是想知道我的结构是否太大了.我想要使用结构的原因是因为我已经知道它们比类更快,我认为我真的需要速度.
我发现如果你的结构太大,它实际上会减慢你的程序,所以我想知道这个指南是什么以及我的结构是否需要转换为类.
public struct Tiles
{
public Rectangle rect;
//i know this wont run with them being initalized like this but if i change to a class this will
//stay like this and im in the middle of deciding what to do
Bitmap currentPic = new Bitmap(50, 50);
ImageAttributes imgAttr = new ImageAttributes();
float[][] ptsArray;
ColorMatrix clrMatrix;
public void setTiles(int i, int k, int width, int height)
{
Rectangle temp = new Rectangle(i, k, width, height);
rect = …Run Code Online (Sandbox Code Playgroud) 我的结构中有一个 DateTime 属性字段。我正在尝试验证输入日期以确保输入的值不是将来的值。
我正在使用以下代码:
public struct Car
{
public DateTime Year
{
get
{
return Year;
}
set
{
if (value > DateTime.Now)
throw new InvalidOperationException("Date cannot be in the futrure");
else
Year = value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我现在尝试运行此代码时,我不断收到 StackOverflowException 并显示消息“无法计算表达式,因为当前线程处于堆栈溢出状态”。
关于为什么会这样或者如何解决这个问题有什么想法吗?
-谢谢。