70

我想在Visual Studio 2008中调试一个程序。问题是,如果它没有获取参数,它就会退出。这是从主要方法:如何在调试时使用参数启动程序?

if (args == null || args.Length != 2 || args[0].ToUpper().Trim() != "RM") 
{ 
    Console.WriteLine("RM must be executed by the RSM."); 
    Console.WriteLine("Press any key to exit program..."); 
    Console.Read(); 
    Environment.Exit(-1); 
} 

我不想评论它,然后回来编译时。如何在调试时使用参数启动程序?它被设置为启动项目。

+0

[Visual Studio C#传递命令行参数]可能的重复(http://stackoverflow.com/questions/6475887/passing-command-line-parameters-with-visual-studio-c-sharp) – horns 2015-05-04 13:49:45

+2

可能的重复[用Visual Studio中的命令行参数调试](http://stackoverflow.com/questions/298708/debugging-with-command-line-parameters-in-visual-studio) – 2015-10-15 09:24:15

回答

130

转到Project-><Projectname> Properties。然后点击Debug选项卡,并在名为Command line arguments的文本框中填写您的参数。

+0

参数可以(必须)是填入'命令行参数'空间分隔(就像使用命令行一样)。我不确定是否有其他方法,但也许可以将其添加到答案中。 – d4Rk 2015-04-01 17:08:10

44

我会建议使用directives类似如下:

 static void Main(string[] args) 
     { 
#if DEBUG 
      args = new[] { "A" }; 
#endif 

      Console.WriteLine(args[0]); 
     } 

祝你好运!

4

我的建议是使用单元测试。

在应用程序中执行以下操作交换机Program.cs

#if DEBUG 
    public class Program 
#else 
    class Program 
#endif 

与同为static Main(string[] args)

或者通过添加

[assembly: InternalsVisibleTo("TestAssembly")] 

AssemblyInfo.cs使用Friend Assemblies

然后创建一个单元测试项目和测试,看起来有点像这样:

[TestClass] 
public class TestApplication 
{ 
    [TestMethod] 
    public void TestMyArgument() 
    { 
     using (var sw = new StringWriter()) 
     { 
      Console.SetOut(sw); // this makes any Console.Writes etc go to sw 

      Program.Main(new[] { "argument" }); 

      var result = sw.ToString(); 

      Assert.AreEqual("expected", result); 
     } 
    } 
} 

这样你可以在一个自动化的方式,测试参数的多个输入,无需编辑您的代码或变化每次你想检查一些不同的菜单设置。

相关问题