e心e意

导航

C# 类与结构

 C#结构体和类的区别技术要点:

    ◆类在传递的时候,传递的内容是位于托管内存中的位置,结构体在传递的时候,传递的内容是位于程序堆栈区的内容。当类的传递对象修改时,将同时修改源对象,而结构体的传递对象修改时,不会对源对象产生影响。

    ◆在一个类中,可以定义默认的、不带参数的构造函数,而在结构体中不能定义默认的、不带参数的构造函数。两者都可以定义带有参数的构造函数,通过这些参数给各自的字段赋值或初始化

代码运行如下:类中赋值以后,两个对象中的值都发生变化,而结构体原来对象的值为发生变化 

namespace STRUCTORCLASS
{

// 参考地址:http://www.cnblogs.com/siri/archive/2012/10/31/2748559.html
public enum Gender
{
男,

}
public struct stuPerson
{
public string stuName;
public int stuAge;
public Gender stuSex;
public void stuSayHello()
{
Console.WriteLine("我是{0},年龄{1},性别{2}",stuName ,stuAge ,stuSex );
}
//必须定义有参数的构造函数
public stuPerson(string name, int age, Gender sex)
{
this.stuName = name;
this.stuAge = age;
this.stuSex = sex;
}
}

class Person
{
public string Name;
public int Age;
public Gender Sex;

public void SayHello()
{
Console.WriteLine("我是{0},年龄{1},性别{2}",this.Name ,this.Age ,this.Sex );
}
public Person()
{ }
public Person(string name, int age, Gender sex)
{
this.Name = name;
this.Age = age;
this.Sex = sex;
}
}
class Program
{
static void Main(string[] args)
{
//实例化类
Person LiuXiang = new Person();
LiuXiang.Name = "刘翔";
LiuXiang.Age = 30 ;
LiuXiang.Sex = Gender.男;
LiuXiang.SayHello();

Person LXSon = LiuXiang;
LXSon.Age = 10;
Console.WriteLine("LiuXiang 年龄{0}",LiuXiang .Age .ToString ());
Console.WriteLine("LXSon 年龄{0}",LXSon .Age .ToString ());

Console.WriteLine();

//结构体
stuPerson YaoMing = new stuPerson("姚明",33,Gender.男 );
YaoMing.stuSayHello();
stuPerson YMSon = YaoMing;
YMSon.stuAge = 13;
Console.WriteLine("YaoMing 年龄{0}",YaoMing .stuAge .ToString ());
Console.WriteLine("YMSon 年龄{0}",YMSon .stuAge .ToString ());

Console.ReadLine();

}
}
}

posted on 2014-12-05 17:51  e心e意  阅读(94)  评论(0编辑  收藏  举报