C#自动属性

来源:互联网 发布:python 编写安装程序 编辑:程序博客网 时间:2024/06/12 01:04

属性是一个非常有用的技术,以C#应用广泛。我们采用手动输入费时费力。vs2008提供了一种快速创建属性的方式,重构/封装字段。首先在一个类中定义一个私有字段,选择这个字段,右击此字段,在弹出的快捷菜单中选择“重构”——“封装字段”命令。

在单击“封装字段”后,在“属性名”文本框中可以修改属性名称,默认是将字段名首字母大写,一般不需要修改,然后单击“确定”按钮。

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

namespace Example_TestPro
{
    class Student
    {
        public string Name
        {
            get;
            set;
        }
       

        public string Sex
        {
            get;
            set;
        }


        public int Age
        {
            get;
            set;
        }
        static void Main(string[] args)
        {
            Student stu = new Student();//创建student对象
            //给stu对象的属性赋值
            stu.Name = "张三丰";
            stu.Sex = "男";
            stu.Age = 20;
           // Student stu = new Student { Name="张三丰",Sex="男",Age=20};
            //将结果输出到控制台
            Console.WriteLine("该学生的姓名={0},性别={1},年龄={2}",stu.Name.ToString(),stu.Sex.ToString(),stu.Age.ToString());
            Console.ReadKey();
        }
    }
}

原创粉丝点击