C#中struct与class的区别

namespace structAndclass
{
class Program
{
static void Main(string[] args)
{
// 区别: struct 在传递的时候,传递是一个副本,并没有修改原始对象
// class 在传递的时候传递的是对原始对象的引用,修改原始对象的值

        StructModifyPoint structModifyPoint = new StructModifyPoint();
        structModifyPoint.y = 10;
        structModifyPoint.x = 10;
        Console.WriteLine("----------Struct--------");
        // values are 10,10
        Console.WriteLine("Initial values are :{0},{1}",structModifyPoint.x,structModifyPoint.y);
        Console.WriteLine("Insurt structChangePoint():");
        // values are 20,20
        structChangePoint(structModifyPoint);
        // values are 10,10
        Console.WriteLine("After Modify,struct values are:{0},{1}", structModifyPoint.x, structModifyPoint.y);

        ClassModifyPoint classModifyPoint = new ClassModifyPoint();
        classModifyPoint.y = 10;
        classModifyPoint.x = 10;
        Console.WriteLine("----------Class--------");
        // values are 10,10
        Console.WriteLine("Initial values are :{0},{1}", classModifyPoint.x, classModifyPoint.y);
        Console.WriteLine("Insurt classChangePoint():");
        // values are 20,20
        classChangePoint(classModifyPoint);
        // values are 20,20
        Console.WriteLine("After Modify,class values are:{0},{1}", classModifyPoint.x, classModifyPoint.y);
        Console.ReadKey();

    }
    //struct
    public static   void structChangePoint(StructModifyPoint point)
    {
        point.x += 10;
        point.y += 10;

        Console.WriteLine("structChangePoint inner values are:{0},{1}",point.x,point.y);
    }
    //class
    public  static void classChangePoint(ClassModifyPoint point)
    {
        point.x += 10;
        point.y += 10;
        Console.WriteLine("classChangePoint inner values are:{0},{1}", point.x, point.y);
    }
}
//结构体

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

}

//类

public class ClassModifyPoint
{
public int x;
public int y;
public ClassModifyPoint()
{

    }

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

}
20 个 C# 热点问题解答>>微软虚拟学院

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值