C#类与对象简单代码

在类和对象中,由于属性是封装的,所以我们要设置get和set函数来调用和设置属性,C#的话,我们可以先声明属性名,然后,选中声明语句,按住ctrl+r再按ctrl+e(VS2010),经过确定,就可以生成set和get函数。具体了解的话,可以看我的代码

  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                Student s = new Student("2017011525","王二狗");
                Console.WriteLine("学号:{0} 姓名{1} 成绩{2}", s.Id, s.Name, s.Score);//这里是调用get方法
                s.Name = "Tom";//这里调用Name里面的set方法;记住就好
                //这里的get和set方法的话,如果是不赋值,就是get,也就是获取,赋值,就是set;
                Student a = new Student();
                Console.WriteLine("学号:{0} 姓名{1} 成绩{2}", a.Id, a.Name, a.Score);//未设置,所以都为默认值
            }
    
        }
        class Student//VS2010中默认public
        {
            private string id;
    
            public string Id
            {
                get { return id; }
                set { id = value; }
            }
            private string name;
    
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            private int score;
    
            public int Score
            {
                get { return score; }
                set { score = value; }
            }
            public  Student(string i="未知",string n="未知",int s=0)//可选参数,未输入,则默认
            {
                id = i;
                name = n;
                score = s;
                
            }
        }
    }

C#类与对象简单代码