为什么以下陈述显然是错误的,但评估为正确?

发布于 2024-11-16 03:00:05 字数 9925 浏览 4 评论 0原文

我有以下代码片段

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;

我猜它太快处理我的对象了?

AddressType:

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 { }
    }
}

I have the following snippet of code

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");

The if statement is always evaluating as true and throwing the exception, even though it is quite clearly false.

Can anyone shed some light as to why this is happening?

Edited:

This code works fine

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;

I'm guessing it's disposing my object too soon?

AddressType:

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

Broken Code:

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

Both of these work

        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;
        //}

Try this code:

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 { }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无声静候 2024-11-23 03:00:05

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

例如

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

You're comparing instances. try using .Equals instead.

e.g.

if (!addr.AddressCode.Equals("SLGTest"))
    throw new Exception("Address code did not match");
心的憧憬 2024-11-23 03:00:05

看来是 IIS 的问题。如果我在控制台应用程序中运行代码,它会完全按照预期工作。如果我创建一个在 Visual Studio Dev Web Server 上运行的 Web 应用程序项目,它可以正常工作。当我切换到 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 { }
        }
    }
}

It appears to be a problem with IIS somehow. If I run the code in a console app, it works exactly as intended. If I create a Web App project running on Visual Studio Dev Web Server it works fine. As soon as I switch over to IIS and create a virtual directory, it fails. I can recreate it in this code. I'm still not sure why, but adding a GC.KeepAlive() fixes the problem.

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 { }
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文