结构体

  关于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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值