场景
C#面向对象,实现简单的类的封装联系代码。
效果
实现
新建窗体项目
拖拽一个Button控件并修改为你好,然后双击Button控件进入其点击事件的代码编写中。
右击项目-添加-类
名字叫Person
Person代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SayHello
{
class Person
{
private int _age;
public int Age {
get { return _age; }
set {
if (value >= 30 && value <= 90)
{
_age = value;
}
else
{
_age = 30;
}
}
}
private string _name;
public String Name {
get { return _name; }
set { _name = value; }
}
/// <summary>
/// 工号
/// </summary>
private string _id;
public string Id
{
get { return _id; }
set { _id = value; }
}
/// <summary>
/// 资历
/// </summary>
private int _yearOfExperience;
public int YearOfExperience
{
get { return _yearOfExperience; }
set { _yearOfExperience = value; }
}
public string SayHi() {
string message;
message = string.Format("大家好,我是{0},今年{1}岁,项目经验 {2}年。",this._name,this._age,this._yearOfExperience);
return message;
}
}
}
然后在上面的点击事件的方法中
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SayHello
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Person p = new Person();
p.Age = 35;
p.Name = "霸道";
p.Id = "0001";
p.YearOfExperience = 28;
MessageBox.Show(p.SayHi());
}
}
}
代码下载
https://download.csdn.net/download/badao_liumang_qizhi/11555303