struct和class的区别(转)

有人问“为什么不能继承System.Guid 中NewGuid方法呢”,答案是很简单的,因为System.Guid 是结构而不是类。

比如定义如下结构和类

 

public   struct  MyType
{
    
public int MyInteger;
}


public   class  Class1 : MyType
{
}


 

这段代码将抛出编译错误内容为 "Class1: cannot inherit from sealed class MyType".

再如下面代码:

 

public   struct  MyType
{
    
public int MyInteger;
}


public   struct  Class1 : MyType
{
}


 

编译错误如下: "Class1: type in interface list is not an interface".


下面列举出微软提供的例子供大家学习

// Copyright (C) 2000 Microsoft Corporation.  All rights reserved.

//  struct2.cs
using  System;

class  TheClass
{
    
public int x;
}


struct  TheStruct
{
    
public int x;
}


class  TestClass
{
    
public static void structtaker(TheStruct s)
    
{
        s.x 
= 5;
    }

    
public static void classtaker(TheClass c)
    
{
        c.x 
= 5;
    }

    
public static void Main()
    
{
        TheStruct a 
= new TheStruct();
        TheClass b 
= new TheClass();
        a.x 
= 1;
        b.x 
= 1;
        structtaker(a);
        classtaker(b);
        Console.WriteLine(
"a.x = {0}", a.x);
        Console.WriteLine(
"b.x = {0}", b.x);
    }

}



这个例子的输出是:

a.x = 1b.x = 5

从这个例子例子可以看出,当一个结构被传递到一个方法时,被传递的只不过是一个副本,而一个类被传递时,被传递的是一个参考.所以a.x=输出的是1,不变,而b.x却变了.

还有的区别就是结构可以不用new来实例化,而类却要.如果你不用new来实例化一个结构,那么所有的字段将仍然处于未分配状态,直到所有的字段被初始化.和类一样,结构可以执行接口.更重要的是,结构没有继承性,一个结构不能从别的类继承,也不能是别的类的基类.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值