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

如何在没有装VS(Visual Studio)的机器上编译运行C#程序

2014-04-14 11:50 393 查看
马上就要过年了,每年过年都要回老家,使用电脑和网络就没有这边这么方便了。想写程序了,都没有一台带Visual Studio的机器,我也不可能给每台机器都安装一个Visual Studio,怎么办呢?

网上搜索了一下,不是说需要Visual Studio的就是说需要.net framework sdk,Visual Studio好几个G,这个sdk也不小,1.3G,我的优盘没法装(优盘大小只有1G L)

SDK其实有很多我不需要的东东,比如文档,其实我需要的只是一个编译器而已,于是我尝试着把csc.exe拷到自己的优盘上,然后拷到老爸的机器上,用控制台一执行,根本无法使用!!一检查,原来他的机器根本没有安装.net framework

于是我就去微软的主页上找到.net framework 3.5 sp1的下载链接(不是SDK)(http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe),这个还比较好,只有231M,下载安装完毕,发现原来压根就不用自己去拷csc.exe了,在C:/WINDOWS/Microsoft.NET/Framework/v3.5下已经有csc.exe了。哈哈!这样一切准备齐全:有编辑器(Windows自带的记事本),有编译器(csc.exe),也有运行环境(.net
framework)

那么怎么来使用csc.exe编译写好的程序呢?

我们可以写一个程序App.cs

using System;

using System.Windows.Forms;

namespace MyApplication

{

class App

{

public static void Main()

{

Application.Run(new Form());

}

}

}

保存在C盘下。然后调出控制台(开始菜单->运行->cmd,回车),在当前位置为C盘的情况下,输入cd C:/WINDOWS/Microsoft.NET/Framework/v3.5,进入该文件夹

输入csc /t:winexe /r:System.dll /r:System.Windows.Forms.dll /out:C:/app.exe C:/App.cs 回车

就能在C盘下看到有app.exe的文件了,点击运行,就能看到Form了。

这里/t的含义是编译得到的文件类型,可以有4种:exe,winexe,library和module。exe表示控制台运行程序,winexe表示windows运行程序,librar为dll,module为module文件。

/r是程序引用的dll,这里我需要引用两个dll:System.dll和System.Windows.Forms.dll,由于这两个dll是.net提供的,所以无需指定路径,如果是非系统注册的dll,就需要指定路径了。

/out是指定输出的文件,如果不指定,编译生成的文件会默认保存到csc.exe所在的文件夹下

下面我们再写两个文件,将它们编译成一个dll供App.exe调用

Test1.cs

using System;

namespace TestDLL

{

public class Test1

{

public String Text

{

get { return m_Text; }

set { m_Text = value; }

}

private String m_Text;

}

}

Test2.cs

using System;

namespace TestDLL

{

public class Test2

{

public Int32 Value

{

get { return m_Value; }

set { m_Value = value; }

}

private Int32 m_Value;

}

}

使用csc编译成Test.dll

csc /t:library /r:System.dll /out:C:/Test.dll C:/Test1.cs C:/Test2.cs

然后修改App.cs为

using System;

using System.Windows.Forms;

using TestDLL;

namespace MyApplication

{

class App

{

public static void Main()

{

Test1 test1 = new Test1();

test1.Text = "This is my test form";

Test2 test2 = new Test2();

test2.Value = 100;

Form f = new Form();

f.Text = test1.Text;

f.Height = test2.Value;

Application.Run(f);

}

}

}

使用csc编译为app.exe

csc /t:winexe /r:System.dll /r:System.Windows.Forms.dll /r:C:/Test.dll /out:C:/App.exe C:/App.cs

运行生成的app.exe文件,得到的结果如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐