C#结构体特性

结构体的定义:

结构体也可以象类一样可以单独定义.
class  a{};
struct a{};

结构体也可以在名字前面加入控制访问符.
publicstruct student{};
internalstruct student{};

如果结构体student没有publice或者internal的声明 类program就无法使用student结构定义 obj对象
如果结构体student的元素没有public的声明,对象obj就无法调用元素x
因为默认的结构体名和元素名是*******类型
程序:
using System;
publicstruct student
    {
      
publicint x;
    };

class program
{
   
publicstaticvoid Main()
    {
     student obj
=new student();
     obj.x
=100;      
    }

};
在结构体中也可以定义静态成员与类中一样,使用时必须用类名,或结构名来调用不属于实例,声明时直接定义.
程序:
using System;
publicstruct student
    {
    
publicstaticint a =10;
    };
class exe
{
publicstaticvoid Main()
    {
     Console.WriteLine( student.a
=100);
    }
};

using System;
classbase
{
publicstruct student
    {
    
publicstaticint a =10;
    };
}
class exe
{
publicstaticvoid Main()
    {
     Console.WriteLine(
base.student.a =100);
    }
};
在结构体中可以定义构造函数以初始化成员,但不可以重写默认无参构造函数和默认无参析构函数
程序:
publicstruct student
    {
      
publicint x;
      
publicint y;
      
publicstaticint z;
      
public student(int a,int b,int c)
        {
            x
=a;
            y
=b;
         student.z
=c;
        }

    };
在结构体中可以定义成员函数。
程序:
publicstruct student
    {
      
publicvoid list()
            {
Console.WriteLine(
"这是构造的函数");
            }

     };
结构体的对象使用new运算符创建(obj)也可以直接创建单个元素赋值(obj2)这是与类不同的因为类只能使用new创建对象
程序:
publicstruct student
    {
      
publicint x;
      
publicint y;
      
publicstaticint z;
      
public student(int a,int b,int c)
        {
            x
=a;
            y
=b;
         student.z
=c;
        }

    };
class program
{
publicstaticvoid Main()
{
  student obj
=new student(100,200,300);
  student obj2;
  obj2.x
=100;
  obj2.y
=200;
  student.z
=300;
}
}

在使用类对象和函数使用时,使用的是引用传递,所以字段改变
在使用结构对象和函数使用时,是用的是值传递,所以字段没有改变

程序:
using System;
class class_wsy
{
   
publicint x;
}
struct struct_wsy
{
   
publicint x;
}
class program
{
   
publicstaticvoid class_t(class_wsy obj)
    {
        obj.x
=90;
    }
   
publicstaticvoid struct_t(struct_wsy obj)
    {
        obj.x
=90;
    }
   
publicstaticvoid Main()
    {
        class_wsy obj_1
=new class_wsy();
        struct_wsy obj_2
=new struct_wsy();
        obj_1.x
=100;
        obj_2.x
=100;
        class_t(obj_1);
        struct_t(obj_2);
        Console.WriteLine(
"class_wsy obj_1.x={0}",obj_1.x);
        Console.WriteLine(
"struct_wsy obj_2.x={0}",obj_2.x);
        Console.Read();
    }
}
结果为:class_wsy obj_1.x
=90
       struct_wsy obj_2.x
=100

posted @ 2013-03-04 10:49  zagelover  阅读(223)  评论(0编辑  收藏  举报