为什么以下语句评估为真,即使它显然是错误的?

时间:2011-06-20 19:40:14

标签: .net c#-4.0 clr

我有以下代码片段

Addresses addresses = new Addresses();
AddressInfo addr = addresses.GetAddressFromID(csTestSecurityToken, addrID);
addr.AddressCode = "SLGTest";
if (addr.AddressCode != "SLGTest")
    throw new Exception("Address code did not match");

if语句总是评估为true并抛出异常,即使它显然是错误的。

有人能说清楚为什么会这样吗?

编辑:

此代码可以正常使用

Addresses addresses = new Addresses();
AddressInfo addr = addresses.GetAddressFromID(csTestSecurityToken, addrID);
addr.AddressCode = "SLGTest";
if (addr.AddressCode != "SLGTest")
    throw new Exception("Address code did not match");

addr = addr;

我猜它太快处理我的物体了?

地址类型:

public class AddressInfo
{
    public enum AddressTypes { Undefined, HomeOwner, Builder, Dealer, Shipping, Main, Billing }
    public AddressInfo() 
    {
        ID = -1;
        AddressCode = string.Empty;
        ResellerID = string.Empty;
        AddressType = AddressTypes.Undefined;
        CompanyName = string.Empty;
        FirstName = string.Empty;
        LastName = string.Empty;
        Address1 = string.Empty;
        Address2 = string.Empty;
        City = string.Empty;
        State = string.Empty;
        Zip = string.Empty;
        Country = string.Empty;
        WorkPhone = string.Empty;
        HomePhone = string.Empty;
        CellPhone = string.Empty;
        Fax = string.Empty;
        EMailAddress = string.Empty;
    }

    public int ID { get; set; }
    public string AddressCode { get; set; }
    public string ResellerID { get; set; }
    public AddressTypes AddressType { get; set; }
    public string CompanyName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    public string Country { get; set; }
    public string WorkPhone { get; set; }
    public string HomePhone { get; set; }
    public string CellPhone { get; set; }
    public string Fax { get; set; }
    public string EMailAddress { get; set; }
}

GetAddressFromID

    [WebMethod]
    public AddressInfo GetAddressFromID(string securityToken, int addressID)
    {
        AddressInfo returnAddress = null;
        string resellerID = Security.ValidateToken(securityToken);

        if (ValidateResellerID(resellerID, addressID) == false)
            throw new Exception("The ResellerID for this address does not match the SecurityToken ResellerID.");

        using (SqlConnection cn = new SqlConnection(DBConnection.ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                // Open the connection
                cmd.Connection = cn;

                try
                {
                    cmd.CommandText = "Select * From Addresses Where ID=@AddressID";
                    cmd.Parameters.AddWithValue("@AddressID", addressID);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet dsAddresses = new DataSet();
                    da.Fill(dsAddresses);

                    returnAddress = (from a in dsAddresses.Tables[0].AsEnumerable()
                                     select new AddressInfo
                                     {
                                         ID = a.Field<int>("ID"),
                                         AddressCode = a.Field<string>("AddressCode"),
                                         ResellerID = a.Field<string>("ResellerID"),
                                         AddressType = (AddressInfo.AddressTypes)Enum.Parse(typeof(AddressInfo.AddressTypes), a.Field<string>("AddressType"), true),
                                         CompanyName = a.Field<string>("CompanyName"),
                                         FirstName = (a.Field<string>("FirstName") == null) ? string.Empty : a.Field<string>("FirstName"),
                                         LastName = (a.Field<string>("LastName") == null) ? string.Empty : a.Field<string>("LastName"),
                                         Address1 = (a.Field<string>("Address1") == null) ? string.Empty : a.Field<string>("Address1"),
                                         Address2 = (a.Field<string>("Address2") == null) ? string.Empty : a.Field<string>("Address2"),
                                         City = (a.Field<string>("City") == null) ? string.Empty : a.Field<string>("City"),
                                         State = (a.Field<string>("State") == null) ? string.Empty : a.Field<string>("State"),
                                         Zip = (a.Field<string>("Zip") == null) ? string.Empty : a.Field<string>("Zip"),
                                         Country = (a.Field<string>("Country") == null) ? string.Empty : a.Field<string>("Country"),
                                         WorkPhone = (a.Field<string>("Phone") == null) ? string.Empty : a.Field<string>("Phone"),
                                         HomePhone = (a.Field<string>("Home") == null) ? string.Empty : a.Field<string>("Home"),
                                         CellPhone = (a.Field<string>("Cell") == null) ? string.Empty : a.Field<string>("Cell"),
                                         Fax = (a.Field<string>("Fax") == null) ? string.Empty : a.Field<string>("Fax"),
                                         EMailAddress = (a.Field<string>("EMailAddress") == null) ? string.Empty : a.Field<string>("EMailAddress")
                                     }).FirstOrDefault<AddressInfo>();

                }
                catch (Exception e)
                {
                    throw new Exception(e.Message + e.StackTrace);
                }
                finally
                {
                    if ((cn != null) && (cn.State != ConnectionState.Closed))
                        cn.Close();
                }
            }
        }

        // We have to get the record first, then determine if the address record resellerid matches the security token resellerid
        if (resellerID != returnAddress.ResellerID)
            throw new Exception("The ResellerID for this address does not match the SecurityToken ResellerID.");

        return returnAddress;
    }

破碎的代码:

    private void TestAddresses()
    {
        int addrID = 39294;

        Addresses addresses = new Addresses();
        AddressInfo addr = addresses.GetAddressFromID(csTestSecurityToken, addrID);
        addr.AddressCode = "Test";
        if (addr.AddressCode != "Test")
            throw new Exception("Address code did not match");

        try
        {
            // Try with SNC's security token.  Should error
            addr = addresses.GetAddressFromID("0AABEE33-8618-4EBA-B07A-5D6C8FFABA11", addrID);
            throw new Exception("Invalid resellerid did not throw correctly.");
        }
        catch (Exception ex)
        {
            if (ex.Message != "The ResellerID for this address does not match the SecurityToken ResellerID.")
                throw ex;
        }


        addr = addresses.GetAddressFromAddressCode(csTestSecurityToken, "SLGTest");
        if (addr.AddressCode != "SLGTest")
            throw new Exception("Address code did not match");          

        addr.Address1 = "16 North";
        addr.City = "Highland";
        addr.State = "UT";
        addr.Zip = "84004";

        addresses.UpdateAddress(csTestSecurityToken, addr);

        addresses.DeleteAddress(csTestSecurityToken, addr.ID);
    }

这两项工作

        Addresses addresses = new Addresses();
        AddressInfo addr = addresses.GetAddressFromID(csTestSecurityToken, addrID);
        addr.AddressCode = "Test";
        if (addr.AddressCode != "Test")
            addrID = 0;  // <--------------------- Changed this

        try
        {
            // Try with SNC's security token.  Should error
            addr = addresses.GetAddressFromID("0AABEE33-8618-4EBA-B07A-5D6C8FFABA11", addrID);
            throw new Exception("Invalid resellerid did not throw correctly.");
        }
        catch (Exception ex)
        {
            if (ex.Message != "The ResellerID for this address does not match the SecurityToken ResellerID.")
                throw ex;
        }
                       -----------------------------------------------------------
        Addresses addresses = new Addresses();
        AddressInfo addr = addresses.GetAddressFromID(csTestSecurityToken, addrID);
        addr.AddressCode = "Test";
        if (addr.AddressCode != "Test")
            throw new Exception("Address code did not match");

        //try
        //{
        //    // Try with SNC's security token.  Should error
        //    addr = addresses.GetAddressFromID("0AABEE33-8618-4EBA-B07A-5D6C8FFABA11", addrID);
        //    throw new Exception("Invalid resellerid did not throw correctly.");
        //}
        //catch (Exception ex)
        //{
        //    if (ex.Message != "The ResellerID for this address does not match the SecurityToken ResellerID.")
        //        throw ex;
        //}

试试这段代码:

public class AddrTest
{
    public string AddressCode { get; set; }
}

public class Test
{
    public void ThrowFail()
    {
        int x = 0;
        AddrTest addrTest = new AddrTest();
        addrTest.AddressCode = "Test";
        if (addrTest.AddressCode != "Test")
            throw new Exception("This shouldn't be executed.");

        try
        {
            x = 1;
        }
        catch { }
    }
}

2 个答案:

答案 0 :(得分:2)

您正在比较实例。尝试使用.Equals。

e.g。

if (!addr.AddressCode.Equals("SLGTest"))
    throw new Exception("Address code did not match");

答案 1 :(得分:1)

以某种方式似乎是IIS的问题。如果我在控制台应用程序中运行代码,它将完全按预期工作。如果我创建一个在Visual Studio Dev Web Server上运行的Web App项目,它可以正常工作。一旦切换到IIS并创建虚拟目录,它就会失败。我可以在这段代码中重新创建它。我仍然不确定原因,但添加GC.KeepAlive()可以解决问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            new Test().ThrowFail();
        }
    }

    public class AddrTest
    {
        public string AddressCode { get; set; }
    }

    public class Test
    {
        public void ThrowFail()
        {
            int x = 0;
            AddrTest addrTest = new AddrTest();
            addrTest.AddressCode = "Test";
            if (addrTest.AddressCode != "Test")
                throw new Exception("This shouldn't be executed.");

            try
            {
                x = 1;
            }
            catch { }
        }
    }
}