[对象和类型]1.结构体和类

Posted on 2009-09-26 12:43  Relax Active  阅读(219)  评论(0)    收藏  举报

相同点:⑴都是创建对象的模板,每个对象都包含数据,并提供处理和访问数据的方法;

        ⑵结构体和类在语法上很相似。

 

不同点:⑴结构体存储在内存的椎栈(stack)上,类存储在椎 (heap) ;

        ⑵结构体使用struct关键字,类使用class关键字。

示例代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Demo9

{

    class Program

    {

        static void Main(string[] args)

        {

            student name1 = new student();

            name1.Name = "john";

            Console.WriteLine(name1.Name);

 

            teacher name2 = new teacher();

            name2.Name = "teacher Wang";

            Console.WriteLine(name2.Name);

           

        }

        struct student               //声明一个student结构体

        {

            string name;

            int age;

            public string Name

            {

                set

                {

                    this.name = value;

                }

                get

                {

                    return this.name;

                }

            }

 

        }

 

        public class teacher       //声明一个teacher

        {

            string name;

            int age;

            public string Name

            {

                set

                {

                    this.name = value;

                }

                get

                {

                    return this.name;

                }

            }

        }

     

    }

}

 

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3