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

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

Published At
Categories with Web编程
Tagged with
comments powered by Disqus