使用命令行将类型生成到模块中
2016-08-20 11:14
405 查看
本文简单的阐述使用命令行命令编译c sharp源码文件,主要在IDE使用有问题的情况使用。使用这种方式做开发有助于锻炼编程能力。
示例代码:
编译示例代码一定要在 Visual Studio 的工具中找到命令行工具,而不是用windows自带的cmd工具。
可以看到,当前工作目录是 D -> Visual Studio,为了方便,可以将示例代码所在的文件 Program.cs 保存到该目录下。
在命令行中输入如下命令编译该cs文件。
csc.exe /out:Program.exe /t:exe /r:MSCorLib.dll Program.cs
其中,
csc.exe,调用编译器编译代码
/out: ,指示生成的目标文件名称
/t: ,指示生成的目标文件类型
/r: ,指示引用的类库文件,MSCorLib.dll包含核心的如System.Console等类型
Program.cs,被编译的文件
此外,由于/out:Program.exe 和 /t:exe 一般是编译器默认的选项,所以不做提示,MSCorLib.dll也是编译器自动加载的程序集,可以不用指示,所以,上述命令可以简化为如下:
csc Program.cs
若经常使用一组不是默认的如 /out:Program.exe 的参数,我们可以吧这些参数放到一rsp 文件中,通过如下命令直接饮用这些参数即可。
csc @MyProjectParams.rsp Program.cs
其中,MyProjectParams.rsp为响应文件,内容如下:
通过编译得到的Program.exe文件可以直接通过如下命令行调用执行
Program
如果用户有多个文件,其中某些cs文件作为工具库使用,可以先生成如MSCorLib.dll一样的包。
首先新建工具类型Calculator.cs
使用如下命令将上述代码文件生成一个程序集
csc /out:CalLibrary.dll /t:library Calculator.cs
在Program.cs文件中使用CalLibrary.dll 中的类型
使用命令行编译该文件
csc /r:CalLibrary.dll Program.cs
得到的Program.exe文件运行结果如下:
示例代码:
using System; public sealed class Program { public static void Main() { Console.WriteLine("Hello Owen!"); } }
编译示例代码一定要在 Visual Studio 的工具中找到命令行工具,而不是用windows自带的cmd工具。
可以看到,当前工作目录是 D -> Visual Studio,为了方便,可以将示例代码所在的文件 Program.cs 保存到该目录下。
在命令行中输入如下命令编译该cs文件。
csc.exe /out:Program.exe /t:exe /r:MSCorLib.dll Program.cs
其中,
csc.exe,调用编译器编译代码
/out: ,指示生成的目标文件名称
/t: ,指示生成的目标文件类型
/r: ,指示引用的类库文件,MSCorLib.dll包含核心的如System.Console等类型
Program.cs,被编译的文件
此外,由于/out:Program.exe 和 /t:exe 一般是编译器默认的选项,所以不做提示,MSCorLib.dll也是编译器自动加载的程序集,可以不用指示,所以,上述命令可以简化为如下:
csc Program.cs
若经常使用一组不是默认的如 /out:Program.exe 的参数,我们可以吧这些参数放到一rsp 文件中,通过如下命令直接饮用这些参数即可。
csc @MyProjectParams.rsp Program.cs
其中,MyProjectParams.rsp为响应文件,内容如下:
/out:Program.exe /t:exe
通过编译得到的Program.exe文件可以直接通过如下命令行调用执行
Program
如果用户有多个文件,其中某些cs文件作为工具库使用,可以先生成如MSCorLib.dll一样的包。
首先新建工具类型Calculator.cs
using System; public class Calculator { public Int32 add(Int32 a, Int32 b) { return a + b; } public Int32 sub(Int32 a, Int32 b) { return a - b; } }
使用如下命令将上述代码文件生成一个程序集
csc /out:CalLibrary.dll /t:library Calculator.cs
在Program.cs文件中使用CalLibrary.dll 中的类型
using System; public sealed class Program { public static void Main() { Calculator cal = new Calculator(); // call the add function Int32 res1 = cal.add(2, 3); // call the sub function Int32 res2 = cal.sub(4, 1); // display the result Console.WriteLine(res1); Console.WriteLine(res2); } }
使用命令行编译该文件
csc /r:CalLibrary.dll Program.cs
得到的Program.exe文件运行结果如下: