第三章 对象和类型
3.1 创建和使用类
3.2 类和结构
3.3 类
1 函数
a. ref 参数
b. out 参数
c. 命名参数
FullName(lastName: "Doe", firstName: "John");
d. 可选参数
e. 方法的重载
2 属性
a. 只读和只写属性
b. 属性的访问修饰符
c. 自动实现的属性
如果属性的set和get没有任何逻辑,就可以使用自动实现的属性。前提是必须设置2个访问器。
3 构造函数
a. 静态构造函数
保证至多运行一次,即在代码引用类之前调用它。通常在一次调用类的任何成员之前调用。
1 class MyClass 2 { 3 static MyClass() 4 { 5 } 6 }
b. 从构造函数中调用其他构造函数
public Car(string description, uini nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string description) : this(description, 4) { }
4 readonly
其规则是可以在构造函数中给只读字段赋值,但不能在其他地方赋值。
3.4 匿名类型
var caption = new {FirstName = "James", MiddleName = "T", LastName = "Kirk"};
3.5 结构
结构不支持继承
编译器总是提供一个无参数的默认构造函数,它是不允许替换的
每个结构都派生自System.ValueType
结构使用初始值会编译错误。
3.6 弱引用
WeakReference mathReference = new WeakReference(new MathTest()); MathTest math = mathReference.Target as MathTest;
3.7 部分类
partical class TheBigClass: TheBigBaseClass, IBigClass partical class TheBigClass: IOtherBigClass 等价 partical class TheBigClass: TheBigBaseClass, IBigClass, IOtherBigClass
3.8 静态类
static class StaticUtilities { public static void HelperMethod() { } }
3.9 Object类
ToString()
GetHashCode()
Equals()
ReferenceEquals()
Finalize()
3.10 扩展方法
扩展方法是静态方法,它是类的一部分,但实际上没有放在类的源代码中。
public static class MoneyExtension { public static void AddToAmount(this Money money, decimal amountToAdd) { money.Amount += amountToAdd; } }
posted on 2014-07-21 18:13 mszhouzhiyong 阅读(79) 评论(0) 收藏 举报
浙公网安备 33010602011771号