结构体

Posted on 2019-03-03 21:44  金色的省略号  阅读(126)  评论(0编辑  收藏  举报

  关于C#中 struct使用new 初始化

  我们实例化一个结构体,使用 new 运算符,这不同于类使用 new 语句,我们知道对一个类使用new语句会在托管堆上分配空间,而struct是值类型,所以应该在栈上为其分配空间 使用 new ,C#会认为结构体中的成员已经得到初始化,字段会被初始化为默认值0,而不是用 new 会被认为没有初始化,使用字段会报错

  但是,如果结构体是类的字段,则会在堆上分配空间

  测试代码1

using System;

public class Program
{    
    public static void Main()
    {       
        Point p1;
        Point p2 = new Point(); 
        //Console.WriteLine("{0},{1}", p1.x, p1.y); //未赋值,编译报错
        Console.WriteLine("{0},{1}", p2.x, p2.y);
    }
}

struct Point{
    public int x; //未对字段赋值,默认值为0
    public int y; //未对字段赋值,默认值为0
}
View Code

  测试代码2

using System;

struct Point
{
    public double x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public double R(){
        return Math.Sqrt(x*x+y*y);
    }
}

class Test
{
    static void Main() {
        Point[] points = new Point[100];

        for (int i = 0; i < 100; i++)
            points[i] = new Point(i, i*i);
    }
}
View Code