为什么变量存储了未分配给它的错误值 [英] How come the variable stores wrong values which are not assigned to it

查看:63
本文介绍了为什么变量存储了未分配给它的错误值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个用户使用的注册asp.net C#应用程序。



在这个Web应用程序中,我有一个名为FarmIdOld的全局变量,应该采用它的值来自同一页面中的标签,其ID为LblFarmID,因此FarmIdOld = LblFarmID.Text; 。此变量用于上传文件/附件的函数,因此将创建一个使用此全局变量FarmIdOld的名称创建的文件夹,然后使用相同的变量创建子文件夹,并将其作为文件的一部分名称。



通常它可以正常工作,没有问题,它存储标签的正确值,并正确创建FTP中的文件夹,子文件夹,文件名用正确的名字



但是经过一段时间后,我发现有些文件夹/子文件夹/文件是用会话名称创建的(登录用户名),以及其他一些没有名字/空名的文件



发生了什么?怎么变量存储错误的值?变量如何获取会话值而我之前没有将会话值分配给此变量?注意:我没有将此变量赋值给任何值,但是标签为FarmIdOld = LblFarmID.Text;



这里是我的代码,代码中的错误在哪里?我是否必须添加任何其他代码以防止在变量中存储错误的值?



I have registration asp.net C# application that is used by multiple users.

In this web application I have a global variable with name FarmIdOld that supposed to take its value from a label in the same page with id LblFarmID so FarmIdOld = LblFarmID.Text; . this variable is used in a function for uploading files/attachments, so there will be a folder created with the name of this global variable FarmIdOld , and then the same variable is used to create sub-folder and also to be a part of the file name.

Usually it works ok with no problems and it stores the correct value of the label , and the folders, sub-folders, files names in FTP are created correctly with the correct names

but after a period of time, I discovered that there are some folders/sub-folders/files are created with the name of the session/(the login username) , and some other files are created with no names/empty names

what happened? and how come that the variable stores wrong values? how the variable take the session value while I didn't assign the session value to this variable before? Note: I didn't ever assign this variable to any value but the lable FarmIdOld = LblFarmID.Text;

here is my code, where is the mistake in the code? do I have to put any additional code to prevent storing wrong values in the variable?

public partial class MultiOwners : System.Web.UI.Page
    {

        string FarmIdOld; // here declare the global variable
        public void uploadingFilesFunction() // this is the function that use it
        {

            //----------------- Start Get File Size --------------------

            FarmIdOld = LblFarmID.Text; // here I assign the value to the varbaile, it is the text of the lable

            Int32 vOldCard = 1;
            Int32 vAgriculturalCard = 1;


            //---------- End Get File Size ----------------------

            try
            {
                // Start Create Folder ----------------------->



                FolderPath = @"~/attachments/" + FarmIdOld; //here I'm creating the folder with the name of the variable FarmIdOld

                bool exists = System.IO.Directory.Exists(Server.MapPath(FolderPath));

                if (!exists)
                    System.IO.Directory.CreateDirectory(Server.MapPath(FolderPath));

            }
            catch (Exception ee)
            {
                LblCatchError.Text = ee.ToString();
            }

            // End Create Folder ---------------------------------------->

            try
            {
                // Start Create SubFolder ---------------------------------------->

                SubFolderPath = @"~/attachments/" + FarmIdOld + @"/" + FarmIdOld; // here I'm creating the sub folder path with the name of the varaible FarmIdOld



                bool exists = System.IO.Directory.Exists(Server.MapPath(SubFolderPath));

                if (!exists)
                    System.IO.Directory.CreateDirectory(Server.MapPath(SubFolderPath));


            }
            catch (Exception ee)
            {
                LblCatchError.Text = ee.ToString();
            }

            // End Create Folder --------------------------------->

            try
            {
                //Start Uploading files --------------->

                //upload files OldCard
                if (FileUploadOldCard.HasFile)
                {
                    // Start Old Card Length
                    vOldCard = FileUploadOldCard.PostedFile.ContentLength;
                    double vCalculateOldCard = vOldCard / 1048576;
                    double vOldCardSize = Math.Round(vCalculateOldCard, 2);
                    // End Old Card Length

                    if (FileUploadOldCard.HasFile && vOldCard < 2100907)
                    {
                        String ext = System.IO.Path.GetExtension(FileUploadOldCard.FileName);

                        if (ext != ".pdf")
                        {
                            LblFileOldCardSize.Text = "Only PDF type allowed";
                            FileUploadOldCard.Enabled = true;

                        }
                        else
                        {
                            string relativePath = SubFolderPath + @"/OldCard_" + FarmIdOld + ext;


                            FileUploadOldCard.SaveAs(Server.MapPath(relativePath));
                            FileUploadOldCard.Enabled = false;

                        }

                    }
                    else if (FileUploadOldCard.HasFile && vOldCard > 2100907)
                    {
                        // Display the length of the OldCard file in a label.    
                        LblErrorOldCardSize.Text = "File must be less than 2MB";
                        LblFileOldCardSize.Text = "current size is " + vOldCardSize.ToString() + " MB";
                        FileUploadOldCard.Enabled = true;
                    }

                }
                else { }
                //end upload files OldCard

                //upload files Agricultural Card

                if (FileUploadAgriculturalCard.HasFile)
                {
                    // Start Agricultural Card Length
                    vAgriculturalCard = FileUploadAgriculturalCard.PostedFile.ContentLength;
                    double vCalculateAgriculturalCard = vAgriculturalCard / 1048576;
                    double vAgriculturalCardSize = Math.Round(vCalculateAgriculturalCard, 2);
                    // End Agricultural Card Length

                    if (FileUploadAgriculturalCard.HasFile && vAgriculturalCard < 2100907)
                    {
                        String ext = System.IO.Path.GetExtension(FileUploadAgriculturalCard.FileName);
                        if (ext != ".pdf")
                        {
                            LblFileAgriculturalCardSize.Text = "Only PDF type allowed";
                            FileUploadAgriculturalCard.Enabled = true;
                        }
                        else
                        {
                            string relativePath = SubFolderPath + @"/MarketingCard_" + FarmIdOld + ext;


                            FileUploadAgriculturalCard.SaveAs(Server.MapPath(relativePath));
                            FileUploadAgriculturalCard.Enabled = false;
                        }
                    }

                    else if (FileUploadAgriculturalCard.HasFile && vAgriculturalCard > 2100907)
                    {
                        // Display the length of the Agricultural file in a label.    
                        LblErrorAgriculturalCardSize.Text = "File must be less than 2MB";
                        LblFileAgriculturalCardSize.Text = "current size is " + vAgriculturalCardSize.ToString() + " MB";
                        FileUploadAgriculturalCard.Enabled = true;
                    }
                }
                else { }
                //end upload files Agricultural Card


                //End Uploading files --------------------------->

            }
            catch (Exception ee)
            {
                LblCatchError.Text = ee.ToString();
            }
        }


protected void BtnAttachments_Click(object sender, EventArgs e)
        {
            try
            {
                uploadingFilesFunction(); // here I retreive the function by Clicking on button
}
            catch (Exception ee)
            {
                LblCatchError.Text = ee.ToString();
            }

        }
}

推荐答案

没有全局变量在.NET中。您引用的对象 FarmIdOld 是非静态(!)类的实例(非静态!),私有(!)成员 MultiOwners 。它甚至不能接近任何可能被描述为全球的东西。您拥有此对象的实例数与类 MultiOwners 类的实例一样多。因此,所提出的问题毫无意义。问题也没有描述。



但是,我可以解释一下,如果你失去了目的,你如何跟踪这个对象的所有修改。将其替换为一些明确支持的属性(即,不是自动实现的):

There is no such thing as "global variable" in .NET. Your object FarmIdOld you refer to is the instance (non-static!), private(!) member of a non-static(!) class MultiOwners. It cannot be even close the anything which could possible be described as "global". You have as many instanced of this object as the instances of the class MultiOwners. Therefore, the question, as formulated makes no sense at all. The problem is also not described.

However, I can explain how you can track all the modifications of this object, if you lost ends. Replace it with some explicitly backed property (that is, not auto-implemented):
public partial class MultiOwners : System.Web.UI.Page {

    string FarmIdOld {
        get { return farmIdOldInstanceBackingField; }
        set {
            farmIdOldInstanceBackingField = value; // break point here
        } //set FarmIdOld
    } //FarmIdOld

    string farmIdOldInstanceBackingField;

    //...
} //class MultiOwners

这将是您的重构,一些变化在代码中保证保持与更改之前相同的语义。

但是现在,您可以使用调试器并设置断点(请参阅上面的代码示例中的注释此处的断点 )。每次在此断点处停止执行时,您都可以查看调试窗口调用堆栈并查看调用的来源。这足以找到目的。



现在,您可能需要再解决一个调试问题。由于您的 FarmIdOld 与global相反:-),您可以拥有多个实例。

您可以标记所有实例调试期间的对象作为唯一对象。为此,在调试Watch或Autos窗口中,您可以添加要监视的对象(如果它不是Auto),并在选择此对象时使用上下文菜单。然后单击 M ake对象ID菜单项。从这一刻起,您可以在下次执行同一行时从其他实例中告诉该对象。



-SA

This will be your refactoring, some change in code which is guaranteed to keep the same semantic as before the change.
But now, you can use the debugger and set a breakpoint (please see the comment in the code sample above "break point here"). Each time you get the execution stopped at this break point, you can look at the debug window "Call stack" and see where the call comes from. This will be enough to find ends.

Now, you may need to solve one more debugging problem. As your FarmIdOld is something opposite to "global" :-), you can have several instanced of it.
You can mark all instances of all objects during debugging as unique objects. For this purpose in the debug "Watch" or "Autos" window, you can add the object to watch, if it is not "Auto", and use context menu when this object is selected. Then click "Make Object ID" menu items. From this moment, you can tell this object from other instances on next execution of the same line.

—SA


这篇关于为什么变量存储了未分配给它的错误值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆