一、属性
在属性的访问声明中:
◆只有set访问器,表明属性的值只能进行设置而不能读出。
◆只有get访问器,表明属性的值是只读的,不能改写。
◆同时具有set访问器和get访问器,表明属性的值的读写都是允许的。
除了使用了abstract修饰符的抽象属性,每个访问器的执行体中只有分号“;”,其它所有属性的get访问器都通过return来读取属性的值,set访问器都通过value来设置属性的值。
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
befor add:x-33
get x: 33
set x:33 a new value 133
get x: 133
befor add:x-133
每次 运行 man.x ,set 或者 get 都会自动运行,对属性进行读或者写。
感觉优点怪怪的,不过确实蛮方便的。
二、异常处理
异常处理貌似和java一样。
执行代码抛出异常,catch捕获异常,finally执行收尾工作(finally不管是否捕获异常都会执行)。
叁、装箱与拆箱
@装箱是将值类型转换为引用类型
@拆箱是将引用类型转换为值类型
@利用装箱和拆箱功能,可通过允许值类型的任何值与 Object 类型的值相互转换,将值类型与引用类型链接起来
装箱 值类型的数据转换为object类
隐式转换
拆箱 将封装的对象转换为值
显式转换
is运算符 <operand> is <type>
<operand> 可转换为<type> true
as运算符 <operand> as <type>
object obj = val; // 装箱:值类型到引用类型
int num = ( int ) obj; // 拆箱:引用类型到值类型
// 被装过箱的对象才能被拆箱???
四、C#通过提供索引器,可以象处理数组一样处理对象。特别是属性,每一个元素都以一个get或set方法暴露。
写了个实验的,好像长了点,晕。。。。个先。。。
...{
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;
}
}