您的位置:首页 > 编程语言 > C#

一点一点学C#2

2016-07-08 21:54 387 查看
关于不同的命名空间:不同的命名空间里相同的类名不产生冲突

using System;

namespace test1
{
class test
{
public void func()
{
Console.WriteLine("in test1");
}
}
}

namespace test2
{
class test
{
public void func()
{
Console.WriteLine("in test2");
}
}
}

class testClass
{
public static void Main(String[] args)
{
test1.test aa = new test1.test();  //命名空间名.类名
test2.test bb = new test2.test();

aa.func();
bb.func();

Console.ReadLine();
}

}


C#预处理指令:指导编译器在实际编译前开始对信息进行处理

格式:①以#开头;②只有空格可以出现在预处理指令之前,且一个指令在一行;③不以;结尾

预处理器指令描述
#define它用于定义一系列成为符号的字符。
#undef它用于取消定义符号。
#if它用于测试符号是否为真。
#else它用于创建复合条件指令,与 #if 一起使用。
#elif它用于创建复合条件指令。
#endif指定一个条件指令的结束。
#line它可以让您修改编译器的行数以及(可选地)输出错误和警告的文件名。
#error它允许从代码的指定位置生成一个错误。
#warning它允许从代码的指定位置生成一级警告。
#region它可以让您在使用 Visual Studio Code Editor 的大纲特性时,指定一个可展开或折叠的代码块。
#endregion它标识着 #region 块的结束。
#define PI
#define val

using System;

namespace test1
{
class test
{
public static void Main(String [] args)
{
#if(PI && val)
Console.WriteLine("PI and val are defined");
#elif(!PI && val)
Console.WriteLine(" val is defined");
#elif(!val && PI)
Console.WriteLine("PI is defined");
#else
Console.WriteLine("PI and val are not defined");
#endif
Console.ReadKey();
}
}
}


C#异常处理:

异常类描述
System.IO.IOException处理 I/O 错误。
System.IndexOutOfRangeException处理当方法指向超出范围的数组索引时生成的错误。
System.ArrayTypeMismatchException处理当数组类型不匹配时生成的错误。
System.NullReferenceException处理当依从一个空对象时生成的错误。
System.DivideByZeroException处理当除以零时生成的错误。
System.InvalidCastException处理在类型转换期间生成的错误。
System.OutOfMemoryException处理空闲内存不足生成的错误。
System.StackOverflowException处理栈溢出生成的错误。
using System;

namespace test1
{
class test1
{
public static void Main(String [] args)
{
int[] A = new int[5] {1,2,3,4,5};
try //将被激活的特定的异常代码块
{
Console.WriteLine(A[5]);
}
catch(IndexOutOfRangeException e) //捕获异常
{
Console.WriteLine("Excption caught:{0}",e);
//throw e; //抛出异常
}
finally //不管异常是否抛出都会执行
{
Console.WriteLine(A[0]);
}

Console.ReadLine();
}
}
}


委托 delegate

using System;

namespace test1
{
delegate int fun(int n);  //委托

class test1
{
static int num = 6;

public static int AddNum(int x)
{
num += x;
return num;
}

public static int MultNum(int x)
{
num *= x;
return num;
}

public static int getNum()
{
return num;
}

public static void Main(String [] args)
{

fun f1 = new fun(AddNum);
fun f2 = new fun(MultNum);
fun f = f1 + f2; //多播

Console.WriteLine("Add:{0}",f1(2));
Console.WriteLine("Mult:{0}",f2(2));
Console.WriteLine("Mul:{0}",f(2));

Console.ReadLine();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#