一、属性 在属性的访问声明中: using System;
using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 ...{ class Man ...{ private int _x; public Man(int xx) ...{ this._x = xx; } public int x ...{ get ...{ Console.WriteLine("get x: {0}", _x); return _x; } set ...{ Console.WriteLine("set x:{0} a new value {1}", _x, value); _x = value; } } public static Man operator ++(Man man) ...{ man.x = man.x + 100 ;//先运行一次 x.get,再运行一次 x.set return man; } } class Program ...{ static void Main(string[] args) ...{ Man man = new Man(33); Console.WriteLine("befor add:x-{0}", man.x);//运行一次 x.get man++; Console.WriteLine("befor add:x-{0}", man.x);//运行一次 x.get return; } } } 运行结果: get x: 33 每次 运行 man.x ,set 或者 get 都会自动运行,对属性进行读或者写。 感觉优点怪怪的,不过确实蛮方便的。 二、异常处理 异常处理貌似和java一样。 执行代码抛出异常,catch捕获异常,finally执行收尾工作(finally不管是否捕获异常都会执行)。 叁、装箱与拆箱 装箱 值类型的数据转换为object类 int val = 100;
object obj = val; //装箱:值类型到引用类型 int num = (int) obj; //拆箱:引用类型到值类型 //被装过箱的对象才能被拆箱??? 四、C#通过提供索引器,可以象处理数组一样处理对象。特别是属性,每一个元素都以一个get或set方法暴露。 写了个实验的,好像长了点,晕。。。。个先。。。 class MyName //姓名对象
...{ private string _first_name; //姓 private string _second_name;//名 public MyName(String first_name, String second_name) ...{//构造函数 this._first_name = first_name; this._second_name = second_name; } public String FirstName ...{//属性 get ...{ return _first_name; } set ...{ this._first_name = value; } } public String SecondName ...{/**/////属性 get ...{ return _second_name; } set ...{ this._second_name = value; } } } class MynameList //测试索引器 ...{ private MyName[] names; public MynameList(int capacity) ...{ this.names = new MyName[capacity]; } public MyName this[String first_name]//用姓索引 ...{ get ...{ // 遍历数组中是否存在该姓的对象,若存在返回第一个找到的对象 foreach (MyName curName in names) ...{ if (curName.FirstName == first_name) return curName; } Console.WriteLine("未找到"); return null; // 使用 null 指示失败 } } public MyName this[int index] //用下标索引 ...{ get ...{ // 验证索引范围 if (index < 0 || index >= names.Length) ...{ Console.WriteLine("索引无效"); return null;// 使用 null 指示失败 } return names[index]; // 对于有效索引,返回请求的对象 } set ...{ if (index < 0 || index >= names.Length) ...{ Console.WriteLine("索引无效"); return; } names[index] = value; } } } 五、委托 |
|