.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
struct和class

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

有人问“为什么不能继承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来实例化一个结构,那么所有的字段将仍然处于未分配状态,直到所有的字段被初始化.和类一样,结构可以执行接口.更重要的是,结构没有继承性,一个结构不能从别的类继承,也不能是别的类的基类.

博客园wljcan的文章
http://www.cnblogs.com/wljcan/archive/2004/04/19/6520.aspx




相关文章

相关软件