在Visual Studio中使用发布功能时,是否可以自动排除代码

时间:2010-04-22 14:35:14

标签: visual-studio compiler-construction publish

当您在visual studio中使用发布功能时,它们是否可以排除代码块。换句话说,我有一个登录按钮,它做了类似的事情:

// Start Exclude when publishing
if (txtUserName.Text == "" && txtPassword.Password == "")
{             
  lp = new System.ServiceModel.DomainServices.Client.ApplicationServices.LoginParameters("UserName", "Password");
}
else
// Stop Exclude when publishing
{
  lp = new System.ServiceModel.DomainServices.Client.ApplicationServices.LoginParameters(txtUserName.Text, txtPassword.Password);
}

这样,当我调试时,我可以将用户名和密码字段留空,只需单击登录,应用程序将登录我。但是当应用程序发布时,编译器会忽略该代码而不将其编译到应用程序中。

3 个答案:

答案 0 :(得分:1)

您可以将Conditional属性与DEBUG常量一起使用,并假设您只发布Release配置中的代码,默认情况下不会定义DEBUG常量,您可以执行以下操作:

static void Main(string[] args)
{
    Login("John", "Doe");
}

public static void Login(string username, string password)
{
    SetDebugCredentials(ref username, ref password);

    // Login here
    Console.WriteLine("Credentials: {0} | {1}", username, password);
}

[Conditional("DEBUG")]
public static void SetDebugCredentials(ref string username, ref string password)
{
    username = "User";
    password = "Password";
}

此代码将在Debug配置中打印User和Password,在Release配置中打印John Doe。

答案 1 :(得分:0)

您可以使用DEBUG常量,该常量应该在项目首选项上处于活动状态。

然后,您可以将代码包装在以下内容中:

 #if DEBUG
    // some code here
 #else
    //other code here
 #endif

如果不需要别人,请不要使用它。

答案 2 :(得分:0)

虽然在这种情况下条件编译和#if开关正常工作,但我认为您实际上在寻找ApplicationDeployment.IsNetworkDeployed属性。

// Check if the application was published via ClickOnce.
if (!ApplicationDeployment.IsNetworkDeployed) {