C# 结构体

StrucrTest.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
    struct MyStruct  // struct定义结构体的关键字. 
    {
        private string name;
        private int age;
        private bool marriage;

        public MyStruct(string n,int a , bool m)  // 这里需要注意. 在结构体的构造方法中,你定义了多少个字段,你就必须得为这些字段全部赋初值,不管你的构造方法中是否有参数,或者参数是否能够和字段完全匹配.
        {
            name = n;
            age = a;
            marriage = m;
        }

        //在结构体中也可以有方法.
        public void show()
        {
            Console.WriteLine("姓名:" + name);
            Console.WriteLine("年龄:" + age);
            if (marriage)
                Console.WriteLine("已婚");
            else
                Console.WriteLine("光棍一个");
        }

        // 结构体当中也可以有属性
        public string Name
        {
            get
            { return name; }
            set
            { name = value; }
        }

        public int Age
        {
            get
            { return age; }
            set
            { age = value; }
        }

        public bool Marriage
        {
            get
            { return marriage;}
            set
            {
                marriage = value;
            }
        }
    }
}

 

Program.cs(程序入口)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
            MyStruct My = new MyStruct("Tony/梦断难寻", 19, true);
            My.show();
            Console.WriteLine("*----------------------------------------*");
            My.Name = "Tony";
            My.Age = 19;
            Console.WriteLine("请输入你的婚姻状态 (Y/N)");
            string y = Console.ReadLine();
            if (y == "Y")
                My.Marriage = true;
            else
                My.Marriage = false;
            My.show();
        }
    }
}

 

 

 

posted @ 2012-10-25 23:23  梦断难寻  阅读(428)  评论(0编辑  收藏  举报