------program.cs--------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 封装
{
class Program
{
static void Main(string[] args)
{
student s = new student();//实例化
teacher t = new teacher();//实例化
Console.WriteLine(t.name);
s.code = "101";
s.score=101;
s.name = "韩可";
s.birthday = DateTime.Now;
//无 返回值 无 参数 直接执行
s.write();
//类里面可以写 , 成员方法成员变量属性,方法分为静态方法、非静态方法等。
int he= s.sum(5, 6);
Console.WriteLine(he);
// s.birthday1 = DateTime.NOW;
// (这句话错误,类里面只设置了get,未设置SET,所以是!只读!属性,不可赋值)
Console.WriteLine(s.code);
Console.WriteLine(s.score);
Console.WriteLine(s.birthday);
Console.WriteLine(s.birthday2);
Console.WriteLine(s.codeandscoresum);
Console.WriteLine(s.name);
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
-------student.cs--------
namespace 封装
{
class student
{
// 1
private string _code;
public string code
{
get { return _code;}
set { _code = value; }
}
//2
private decimal _score;
public decimal score
{
get { return _score;}
set {
if (value < 0 || value > 100)
{
_score = 0;
}
else
{
_score = value;
}
}
}
//3
private DateTime _birthday;
public DateTime birthday
{
get { return _birthday;}
set { _birthday = value;}
}
//4 添加后缀名时系统认定为(后缀名)而不是(新的变量)
public string birthday2
{
get { return _birthday.ToString("yyyy年mm月dd日"); }
}
//5
public string codeandscoresum
{
get{return _code+score;}
}
//6 private string _name;
// public string name; 注释掉,改为简写方式
// public string name { get; set; }
//7 加中文注释
private string _name;
/// <summary>
/// 学生姓名
/// </summary>
public string name
{
get { return _name; }
set { _name = value; }
}
//8 无返回值的写法
public void write()
{
Console.WriteLine("我是STU的write 方法");
}
//9 求和方法
/// <summary>
/// 求和方法
/// </summary>
/// <param name="a">第一个数</param>
/// <param name="b">第二个数</param>
/// <returns></returns>
public int sum(int a, int b)
{
return a+b;
}
//10 面向对象团队级开发
//11 构造函数
}
}
--------teacher.cs-----------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 封装
{
class teacher
{
//构造函数
public teacher()
{
_name = "张三";
}
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
}
}