c#属性(Property)
程序员文章站
2022-06-21 20:31:01
属性(Property)是类(class)、结构(structure)和接口(interface)的命名(named)成员。类或结构中的成员变量或方法称为 域(Field)。属性(Property)是域(Field)的扩展,且可使用相同的语法来访问。它们使用 访问器(accessors) 让私有域的 ......
属性(property)是类(class)、结构(structure)和接口(interface)的命名(named)成员。类或结构中的成员变量或方法称为 域(field)。属性(property)是域(field)的扩展,且可使用相同的语法来访问。它们使用 访问器(accessors) 让私有域的值可被读写或操作。
该代码主要是帮助读者了解属性的用法,代码实现了添加属性值和根据添加的属性值进行筛选
using system; using system.collections; using system.collections.generic; using system.globalization; using system.linq; using system.text; namespace 编码练习 { //创建一个类包含两个属性 class people { public string name { get; set; } public string address { get; set; } public people(string name, string address) { this.name = name; this.address = address; } } //继承两个接口(枚举/格式化) class peoples : ienumerable { //创建一个对象列表 private list<people> lpeoples { get; set; } private stringbuilder sbuilder { get; set; } public peoples() { lpeoples = new list<people>(); } //创建一个可以往列表加属性实例的方法 public void add(people people) { lpeoples.add(people); } //获取对象值 public ienumerator getenumerator() { foreach (var p in lpeoples) { yield return p; } } public override string tostring() { return getcontent(lpeoples); } public string tostring(string format) { return tostring(format, cultureinfo.createspecificculture("zh-cn")); } public string tostring(string format, iformatprovider formatprovider) { ienumerable<people> ps = lpeoples; if (format.toupperinvariant() == "b") { ps = from p in lpeoples where p.address == "北京" select p; } else if (format.toupperinvariant() == "s") { ps = from p in lpeoples where p.address == "上海" select p; } return getcontent(ps); } //将数据连接到数组 private string getcontent(ienumerable<people> peoples) { sbuilder = new stringbuilder(); foreach (var p in peoples) { sbuilder.appendline(string.format("{0}{1}", p.name, p.address)); } return sbuilder.tostring(); } } public class start { public static void main() { peoples peoples = new peoples() {new people("zhangsan","北京"),new people("lisi","上海"),new people("wangwu","北京"),new people("naliu","北京")}; console.writeline("本站会员有:"); console.writeline(peoples.tostring()); console.writeline("北京的会员有:"); console.writeline(peoples.tostring("b")); console.writeline("上海的会员有:"); console.writeline(peoples.tostring("s")); console.readline(); } } }
附加知识:
iformatprovider接口的引用,该接口用于格式化操作,当进行数字,日期时间,字符串匹配时,都会进行cultureinfo的操作,文中cultureinfo.createspecificculture("zh-cn")意为结果输出的是<简体,中国>