C# 属性
访问器(Accessors)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApp2
{class Student{private string code = "N.A";private string name = "not known";private int age = 0;public string Code{get{return code;}set{code = value;}}// 声明类型为 string 的 Name 属性public string Name{get{return name;}set{name = value;}}// 声明类型为 int 的 Age 属性public int Age{get{return age;}set{age = value;}}public override string ToString(){return "Code = " + Code + ", Name = " + Name + ", Age = " + Age;}}class Test{public static void Main(){//创建一个新的Student对象Student s = new Student();//设置student的code、name、ages.Code = "001";s.Name = "Sofiya";s.Age = 1;Console.WriteLine("Student Info:{0}", s);//添加年龄s.Age += 8;Console.WriteLine("Student Info:{0}", s);Console.ReadKey();}}
}
运行结果
抽象属性(Abstract Properties)
抽象类可拥有抽象属性,这些属性应在派生类中被实现。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApp2
{public abstract class Person{public abstract string Name{get;set;}public abstract int Age{get;set;}}class Student:Person{private string code = "N.A";private string name = "not known";private int age = 0;public string Code{get{return code;}set{code = value;}}// 声明类型为 string 的 Name 属性public override string Name{get{return name;}set{name = value;}}// 声明类型为 int 的 Age 属性public override int Age{get{return age;}set{age = value;}}public override string ToString(){return "Code = " + Code + ", Name = " + Name + ", Age = " + Age;}}class Test{public static void Main(){//创建一个新的Student对象Student s = new Student();//设置student的code、name、ages.Code = "001";s.Name = "Sofiya";s.Age = 1;Console.WriteLine("Student Info:{0}", s);//添加年龄s.Age += 8;Console.WriteLine("Student Info:{0}", s);Console.ReadKey();}}
}