结构小记

来源:互联网 发布:大理石 氡气 知乎 编辑:程序博客网 时间:2024/06/08 12:37
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace StructTest{    class Program    {        //可以定义在类内        public struct Test        {            public int test;        }        static void Main(string[] args)        {            //使用new实例化结构对象,分配空间并调用默认无参构造函数初始字段            Person p = new Person(122);            p.Weight = 125;            //p.Test();            Console.WriteLine(p.Weight);            //不使用new,分配空间但没有初始值,不可以直接使用,需要先赋值            Test t;            //[1]不可以直接使用            //Console.WriteLine(t.test);            //[2]可以直接赋值,然后使用            //t.test = 20;            //Console.WriteLine(t.test);            Console.Read();        }    }    //可以与类同级,值类型,不可以被继承,声明字段时不可以初始化    //可以声明带参构造函数(所有字段必须在内初始化),不可以显示声明无参构造函数    //可以定义属性、方法    public struct Person    {        //不能对字段初始化,但可以在方法、有参构造函数中赋值        private int weight;        //如果定义了有参构造函数,则必须在其内部将所有字段初始化,但不可以显示定义无参构造函数        public Person(int weight)        {            this.weight = weight;            Console.WriteLine("Struct_Constructor_Param");        }        //可以有属性        public int Weight        {            get { return this.weight; }            set { this.weight = value; }        }        //可以有方法        public void Test()        {            weight = 1;            Console.WriteLine("Struct_Method-Weight:" + weight);        }    }}


原创粉丝点击