首页 文章

调试时如何启动带参数的程序?

提问于
浏览
79

我想在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);
}

我不想评论它,然后在编译时再回来 . 调试时如何用参数启动程序?它被设置为StartUp Project .

3 回答

  • 4

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

  • 143

    我建议使用directives如下:

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

    祝好运!

  • 47

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

    在您的应用程序中,在 Program.cs 中执行以下开关:

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

    static Main(string[] args) 也一样 .

    或者通过添加使用Friend Assemblies

    [assembly: InternalsVisibleTo("TestAssembly")]
    

    到你的 AssemblyInfo.cs .

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

    [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);
            }
        }
    }
    

    这样,您可以以自动方式测试多个参数输入,而无需在每次要检查不同内容时编辑代码或更改菜单设置 .

相关问题