C#复习⑦

C#复习⑦

2016年6月22日

11:50

Main Exception & Namespaces & Assemblies 异常 & 命名空间 & 程序集

1.try 语句

举例说明

FileStream s = null;

try {

s = new FileStream(curName, FileMode.Open);

...

} catch (FileNotFoundException e) {

Console.WriteLine("file {0} not found", e.FileName);

} catch (IOException) {

Console.WriteLine("some IO exception occurred");

} catch {

Console.WriteLine("some unknown error occurred");

} finally {

if (s != null) s.Close();

}

注意:

catch语句的执行是顺序执行的;

finally语句总会被执行;

在捕获子句中可以省略异常参数名称;

异常类都继承自System.Exception;

2.System.Exception

属性:

e.Message        the error message as a string;
                set by new Exception(msg);

e.StackTrace        trace of the method call stack as a string

e.Source        the assembly that threw the exception

e.TargetSite        the method that threw the exception

方法:

e.ToString()         returns the name of the exception and the StackTrace

3.Throwing an Exception抛出异常

通过非法操作:

除以0操作;

下表越界;

调用空引用;

通过throw语句:

throw new MyException(10);

class MyException : ApplicationException {

public int errorCode;

public MyException(int x) { errorCode = x; }

}

4.异常类

clip_image002

5.catch语句的搜索路径

clip_image004

clip_image006

6.C#异常与Java异常的对比

clip_image008

7.委托中的异常以及多播委托中的异常

委托中的异常处理:

clip_image010

多播委托中的异常处理:

clip_image012

8.C# Namespaces VS Java Packages

clip_image014

clip_image016

9.Assemblies

Assembly: 版本控制的最小单元;动态加载的最小单元;

包括manifest、codes + Metadata

clip_image018

9.Namespaces VS Assemblies

Namespaces: 编译时构造;控制可见性;

Assemblies: 运行时构造;控制动态加载以及版本控制;可能包含来自不同Namespaces下的类型;

clip_image020

clip_image022

10.Compiler Options 编译时指令选择

clip_image024

clip_image026

11.Versioning of Assemblies 版本控制

版本号存储在Assembly中,每次Assembly加载都会进行版本号的检查

clip_image028

12.Private and Public Assemblies

Private Assembly:

只能被一个应用程序使用;

is used by only one application

保存在应用程序目录中;

resides in the application directory

没有强命名;

does not have a "strong name"

无法签名;

cannot be signed

Public Assembly (or shared assembly):

可以被所有应用程序使用;

can be used by all applications

保存在全局Assembly中

resides in the Global Assembly Cache (GAC)

必须有一个强命名;

must have a "strong name"

可以签名;

can be signed

GAC保存着各种相同名字的Assemblies但是有着不同的版本号;

GAC can hold assemblies with the same name but with different version numbers

13.Strong Names & Signing Assemblies &Checking the Signature

强命名包括四个部分:

Assembly的命名

Assembly的版本号;

Assembly的文化属性;

Assembly的公钥。

(1) Generate a key file with sn.exe (Strong Name Tool)

(2) Sign the assembly with the AssemblyKeyFile attribute

clip_image030

即使是在相同的namespace下如果被internal修饰的类命名在不同的Assembly下也是不可以使用的。

clip_image032

原文地址:https://www.cnblogs.com/zpfbuaa/p/5606840.html