(2)定义类
public class Person { public Person() { } public Person(string name, int age) { _name = name; _age = age; } private string _name; public string Name { get { return _name; } set { _name = value; } } private int _age; public int Age { get { return _age; } set { _age = value; } } }
|
(3)定义结构
//可以继承自接口,不可继承类或结构 struct Family: IPerson { public string name; public int age; public bool sex; public string country; public Person person; //不可以包含显式的无参构造函数和析构函数 public Family(string name, int age, bool sex, string country, Person person) { this.name = name; this.age = age; this.sex = sex; this.country = country; this.person = person; } //不可以实现protected、virtual、sealed和override成员 public void GetSex() { if (sex) Console.WriteLine(person.Name + " is a boy."); else Console.WriteLine(person.Name + " is a girl."); } public void ShowPerson() { Console.WriteLine("This is {0} from {1}", new Person(name, 22).Name, country); } //可以重载ToString虚方法 public override string ToString() { return String.Format("{0} is {1}, {2} from {3}", person.Name, age, sex ? "Boy" : "Girl", country); } }
|
(4)测试结构和类
 |
| 图2 |
猜猜运行结果如何,可以顺便检查检查对这个概念的认识。
4.2、.NET研究
在.NET框架中,System.Drawing命名空间中的有些元素,如System.Drawing.Point就是实现为struct,而不是class。其原因也正在于以上介绍的各方面的权衡,大家可以就此研究研究,可以体会更多。另外,还有以struct实现的System.Guid。
5、结论
对基本概念的把握,是我们进行技术深入探索的必经之路,本系列的主旨也是能够从基本框架中,提供给大家一个通向高级技术的必修课程。本文关于class和struct的讨论就是如此,在.NET框架中,关于class和struct的讨论将涉及到对引用类型和值类型的认识,并且进一步将触角伸向变量内存分配这一高级主题,所以我们有必要来了解其运行机制,把握区别和应用场合,以便在平常的系统设计中把握好对这一概念层次的把握。
另外,请大家就以下问题进行讨论,希望能够更加清晰本文的拓展:
◆struct还主要应用在哪些方面?
◆C++和C#中,关于struct的应用又有所不同,这些不同又有哪些区别?
【相关文章】
【责任编辑:
火凤凰 TEL:(010)68476606】
(0票)
(0票)
(0票)
(0票)
(0票)
(0票)