C#高级编程(第七版)读书笔记(3)
1.命名空间别名:
using alias= NamespaceName;
使用时,要用“::”引用,alias::NamespaceExample
2.给main()传递参数
书上例子:
ArgsExample.cs
using System;
namespace Wrox
{
class ArgsExample
{
public static int Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine(args[i]);
}
return 0;
}
}
}
编译:csc ArgsExample.cs
在编译器上输入:ArgsExample /a /b /c
输出结果:
/a
/b
/c
3.其他编译的C#文件
// MathLibrary.cs
namespace Wrox
{
///<summary>
/// Wrox.Math class.
/// Provides a method to add two integers.
///</summary>
public class MathLib
{
///<summary>
/// The Add method allows us to add two integers
///</summary>
///<returns>Result of the addition (int)</returns>
///<param name="x">First number to add</param>
///<param name="y">Second number to add</param>
public int Add(int x, int y)
{
return x + y;
}
}
}
输入:csc /t:library MathLibrary.cs
获得 MathLibrary.dell文件
选择/r编译它
//MathClient.cs
using System;
namespace Wrox
{
class Client
{
public static void Main()
{
MathLib mathObj = new MathLib();
Console.WriteLine(mathObj.Add(7,8));
}
}
}
输入:csc MathClient.cs /r:MathLibrary.dell
输入:MathClient
输出结果:15
4.I/O
Console.Write();
Console.WriteLine();//有换行
使用格式{n,w},n是参数索引,w是宽度值
例如:
int i=940;
int j=73;
Console.WriteLine("{0,4}\n+{1,4}\n——\n{2,4}",i,j,i+j);
规定格式输出:{:},冒号后面要填的就是格式
如:
Console.WriteLine(“{0:#.00}”,0.234);//结果为0.23
还可以添加以下格式代码:
如:Console.WriteLine(“{0,9:C2}”,0.234);//结果为: $0.23
5.条件编译#if,#elif,#else,#endif
注意:只有#elif,而不是else if
一起配合使用的是#define和#undef,表示定义和删除定义,这个被定义的量,只在编译的时候存在,实际代码不存在。
当编译器遇到这些时,会去查找这些代码中的参数是否存在,如果不存在则不进行编译,减少可执行文件的大小。
如:
#define DEBUG
#if DEBUG
ConsoleWriteLine(“Hello!”);
#endif
其他带#的关键字:
#Warning和#error:警告和错误
#region和#endregion:把一段代码,标记成一个名称
#Line和#pragma:不常用