将以下内容复制并粘贴到VS中的新控制台应用程序中.添加对System.Web和System.Web.Services的引用(我知道控制台应用程序不需要这些程序集,我只是向您展示一些在我的Web应用程序中不起作用的代码片段).
尽管if语句中的两个条件都是错误的,但结果却是正确的.谁知道原因?(Visual Studio 2008 9.0.30729.1).NET 3.5 SP1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Services;
using System.Web;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
string x = "qweqweqw";
string y =
"{\"textMedia\":[-1,-1,-1,-1,-1],\"textOperand\":[1,1,1,1,1],\"textString\":[\"\",\"\",\"\",\"\",\"\"],\"dateSite\":[-11],\"dateOperand\":[],\"dateString\":[],\"status\":[-11,0,0],\"media\":[-11,0,0],\"subItem\":true,\"context\":false,\"branchSearch\":false,\"profileIDs\":[2,5,18],\"profileViewIDs\":[48,58,38],\"currentSelectedBranch\":0}";
SaveSearch(x, y);
}
[WebMethod]
public static object SaveSearch(string name, string encodedSearch)
{
object response = new { };
string x = name;
string y = encodedSearch;
// Why does this if statement throw an exception if both equal false?
if (x.Trim().Equals(string.Empty) || y.Trim().Equals(string.Empty))
throw new AjaxErrorException("Save Search", "Something went wrong", "JSFunction");
try
{
{
return new
{
error = false,
name = name,
userID = 123,
date = DateTime.Now
};
}
}
catch (Exception ex)
{
String e;
if (HttpContext.Current.IsDebuggingEnabled)
e = ex.Message + "\n\n" + ex.StackTrace;
else
e = "error error aliens approaching";
throw new AjaxErrorException("Save Search", e, "");
}
return response;
}
public class AjaxErrorException : System.Exception
{
public AjaxErrorException(string title, string details, string function)
: base(title)
{ }
string _stackTrace;
public override string StackTrace
{
get
{
return _stackTrace;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我实际检查,虽然调试器步入if(throw语句)之后的语句,但它实际上并没有抛出异常.我怀疑它是IDE,IL生成和调试器之间的不一致,特别是对于throw语句.如果你尝试其他类型的声明,你实际上没有看到问题.它似乎与这篇文章有关 如果在Visual Studio 2008中声明怪异
我在下面的if块中插入了assert语句,以确保没有触发断言.
System.Diagnostics.Debug.Assert(false);
Run Code Online (Sandbox Code Playgroud)