点点滴滴访问量:
C#中,结构可以看做是简化了的类。结构基本与类相同,也可以有属性、方法、构造函数等成员,但结构更适用于定义单纯的数据结构。例如,定义一个点的坐标。

结构声明使用关键字struct

在使用结构时需要注意:

1、 不能为结构定义无参数的构造函数。总是使用默认构造函数以将结构成员初始化为它们的默认值。

2、 不能在声明字段时为字段赋值,而是要在带参数的构造函数中初始化它们的值。

3、 结构不支持继承。

4、 结构是值类型,虽然结构的初始化也使用了new关键字,可是结构对象依然分配在堆栈上而不是堆上。也可以不使用new关键字,那么在初始化所有字段之前,字段将保持未赋值状态,且不可用。

5、 堆栈的执行效率比堆的执行效率高,可是堆栈的资源有限,不适合处理大的逻辑复杂的对象。结构一般用于表示如点、矩形和颜色这样的轻量对象,当某类型只包含一些数据时,结构也是最佳的选择。

 

例:

using System;

 
namespace jiegou
{
    
public struct Point
    
{
        
public int x,y;
        
public Point(int p1,int p2)
        
{
            x 
= p1;
            y 
= p2;
        }

    }

    
class Class1

    
{
        [STAThread]
        
static void Main(string[] args)

        
{
            Point myPoint 
= new Point();
            Point yourPoint 
= new Point();
            Point hisPoint;
            hisPoint.x 
= 20;
            hisPoint.y 
= 15;

            Console.Write(
"My Point: ");
            Console.WriteLine(
"x = {0},y = {1}",myPoint.x,myPoint.y);
            Console.Write(
"your Point: ");
            Console.WriteLine(
"x = {0},y = {1}",yourPoint.x,yourPoint.y);
            Console.Write(
"his Point: ");
            Console.WriteLine(
"x = {0},y = {1}",hisPoint.x,hisPoint.y);
        }

    }

}

posted on 2006-04-13 16:39  sopper  阅读(457)  评论(0编辑  收藏  举报