第一章杂记
1.Working with Assemblies and Modules
没有想到第一章这里这么郁闷,全英文,理解有点困难,先跳过吧
第二章杂记
1.Boxing and Unboxing
引用的用处好大呀,看看下边这段代码,知道里面发生了几次boxing和unboxin吗
using System; class test { public static void Main() { int i = 42; // Simple unboxed value type object o = i; // Will cause a boxing operation of i Console.WriteLine(i + ", " + (Int32)o); } }
一共发生了3次封装
object o = i;这里是一处
i+","+(Int32)o中,首先需要使用string::Concat把几个参数连接成一个字符串,Concat的重载函数中,
调用参数为object的重载函数,i到object发生一次box,接着","push进来,o由于先转为Int32,需要
先unboxing,再boxing,最后连接成一个字符串。
2.类型转换
简单的不提了,提提类之间的转换吧,继承类可以代替基类,而基类不能代替继承类,因为继承类的接口可能
没有基类没有实现,但是使用转换就可以,但是转换虽然在编译阶段不会报错,但是在运行时刻会抛出
System.InvalidCastException,因此出现了一个as,实在是个好东东呀,不用担心再抛出异常了,
会把不能转换的自动赋值为null,看代码吧
class Employee { } class ContractEmployee : Employee { } class CastExample1 { public static void Main () { Employee e = new ContractEmployee();//用继承类代替一个基类,编译通过
ContractEmployee ce = new Employee(); //基类代替继承类,编译失败
ContractEmployee ce = (ContractEmployee)new Employee(); //编译通过但运行出错
ContractEmployee c = e as ContractEmployee;//效果同上,但运行是没有异常,c为null
} }
3.和C++里面有点区别呀
如果ClassName是一个类的名字
ClassName test1;在c++中就是堆栈中开辟了一段空间,但是C#中只是声明了一下,并没有开辟空间
ClassName test2=new ClassName();在c++中是在堆中开辟了一块空间,而C#中无论在哪里开辟,
都要使用new。
4.常数变量和只读变量
const和readonly,const早已见过,readonly第一次看到
const默认即为static的,无须实例化一个类即可访问,readonly需要实例化一个类,看下面的例子
using System;
using System.Net;
class Workstation
{
public Workstation()
{
IPAddress ipAddress =
Dns.Resolve(HostName).AddressList[0];
IPAddressString = ipAddress.ToString();
}
public const string HostName = "cosette";
public readonly string IPAddressString;
}
class GetIpAddress
{
public static void Main()
{
Workstation workstation = new Workstation();
Console.WriteLine("The IP address for '{0}' is {1}",
Workstation.HostName, workstation.IPAddressString);
}
}
使用workstation才可以访问IPAddressString,而HostName可以使用Workstation访问。
如果需要一个静态的readonly对象,简单,在readonly前面加上一个static就可以了
readonly和const的区别在于赋值时刻的不同,const是在编译时赋值,而readonly在运行时刻赋值
赋值后都不能改变。
5.sealed关键字
不想你的类被其他的类继承吗,那么在类前面加上sealed吧
sealed class Point
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public int X;
public int Y;
}
6.struct和class的区别
struct可以不用new就可以访问
struct RGB
{
public int Red;
public int Green;
public int Blue;
}
RGB rgb;
rgb.Red = 0xFF;
rgb.Green = 0xFF;
rgb.Blue = 0xFF;
但未经赋值的struct不能访问
RGB rgb; // ERROR: Use of unassigned field
Console.WriteLine(rgb.Red);
下面的就可以,由于new的过程中向struct中的成员赋值
RGB rgb = new RGB();
Console.WriteLine(rgb.Red);
感觉上就是类的缩水版,不能被继承,默认继承自System.ValueType类,可以有自己的构造函数,构造函数
的参数必须是这个结构体的所有成员,看代码
struct RGB
{
// 构造函数错误
public RGB();
public int Red;
public int Green;
public int Blue;
}
//正确的方法
struct RGB
{
public RGB(int red, int green, int blue)
{
Red = red;
Green = green;
Blue = blue;
}
public int Red;
public int Green;
public int Blue;
}