【转】C#类中有字段,属性,方法
转自:https://www.cnblogs.com/zywf/p/4492689.html
类中可以存放字段、属性和方法,
属性中get和set
get访问器用于对字段的取值进行限定,返回属性值;
set访问器用于对字段的赋值进行限定,分配新值;
person类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { class Person { //这里是字段用来存储数据,private可写可不写 private string _name; int _age; char _gender; //这里是属性,本身没值,用于给字段赋值与取值时的方法,但不能称之为方法 public string Name { get { return _name; } set { _name = value; } } public int Age { //取值时进行判断 get { if (_age < 0 || _age > 100) { return _age = 0; } return _age; } set { _age = value; } } public char Gender { get { return _gender; } //赋值时进行判断 set { if (value != '男' && value != '女') { value = '男'; } _gender = value; } } public void XingWei() { Console.WriteLine("姓名:{0},年龄:{1},性别:{2}", this.Name, this.Age, this.Gender); } } }
class1类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { static void Main(string[] arr) { Person xinRen = new Person(); xinRen.Name = "张飞"; xinRen.Age = 190; xinRen.Gender = '春'; xinRen.XingWei(); Console.ReadKey(); } } }
【推荐】
C# 中类的成员有哪些?
https://www.cnblogs.com/211Lh/p/10840658.html
qq:527592435