c# - 没有运行YET的代码导致异常?这怎么可能? [英] c# - Code that HAS NOT RUN YET is causing an exception? How is this even possible?

查看:240
本文介绍了c# - 没有运行YET的代码导致异常?这怎么可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我完全傻了这个。我收到错误对象引用未设置为对象的实例。,我不知道为什么。

So I am completely stumped on this one. I am getting an error Object reference not set to an instance of an object. and I am not sure why.

我有一个类 FILE

    public class FILE
    {
        private string _fileName;
        public string fileName
        {

            get
            {
                if (!Settings.Values.CaseSensitive)
                    return this._fileName.ToUpper();
                else
                    return this._fileName;
            }
            set
            {
                if (!Settings.Values.CaseSensitive)
                    this._fileName = value.ToUpper();
                else
                    this._fileName = value;
            }
        }
        public string folderName { get; set; }
        public byte[] fileHashDigest { get; set; }
    }

我正在创建一个类似于

FILE test1233;      
test1233 = new FILE(); // <---- Ex thrown here!? Why???    
test1233.fileName = "";
folderName = "";
fileHashDigest = new byte[1];

只要变量放在堆栈上,它会抛出异常。但是,如果我删除所有代码进一步下降的代码(没有被执行在DEBUGMODE !!!),然后没有异常抛出。这个地方在做什么?

As soon as the variable is placed on the stack, it throws an exception. BUT... if I remove all refrences to this variable on code further down (WHICH HAS NOT YET BEEN EXECUTED IN DEBUGMODE!!!) then no exception gets thrown. What on earth is going on here?

对于参考,这里是全部的方法:

For refrence, here is the method in it's entirety:

    private bool IsFolderOverride(FileCollection zipFILEList, DataTable exceptionTableFileList, DataRow currentRow, ref DataTable detectedFolderRenames)
    {
        bool foundInExceptionTable = false;
        foreach (DataRow exRow in exceptionTableFileList.Rows)
        {
            if (exRow["FILE_NAME"].ToString().ToUpper() == currentRow["FILE_NAME"].ToString().ToUpper() &&
                (decimal)exRow["WINDOW_GROUP_ID"] == (decimal)currentRow["WINDOW_GROUP_ID"])
            {
                string name = exRow["FILE_NAME"].ToString().ToUpper();
                string folder = exRow["FOLDER_NAME"].ToString().ToUpper();
                byte[] digest = (byte[])exRow["FILE_HASH_DIGEST"];
                CopyCat exCopyCat = new CopyCat();
                exCopyCat.fileName = name;
                exCopyCat.folderName = folder;
                exCopyCat.fileHashDigest = digest;

                //HAS AN EXCEPTION!
                FILE test1233 = new FILE();
                test1233.fileName = "";
                test1233.folderName = "";
                test1233.fileHashDigest = new byte[1];

                //NO EXCEPTION THROWN
                FILE test = new FILE();
                bool test9 = zipFileList.Contains(test1233);


                test.fileName = name;
                test.folderName = folder;
                test.fileHashDigest = digest;

                FILE test123 = new FILE();

                if (zipFileList.Contains(test1233)) // Exact match found in zip in old folder from exception table.
                {
                    FILE exists = zipFileList.Where(f => f.fileName == test1233.fileName &&
                                          f.fileHashDigest.SequenceEqual(test1233.fileHashDigest)).First();
                    object[] items = exRow.ItemArray;
                    Array.Resize(ref items, items.Length + 4);
                    items[items.Length - 1] = "Y";
                    items[items.Length - 2] = exists.folderName;
                    items[items.Length - 3] = test1233.folderName;
                    items[items.Length - 4] = "Folder Override";
                    if (detectedFolderRenames.Rows.Count == 0 || !detectedFolderRenames.Rows.Contains(items[0]))
                        detectedFolderRenames.Rows.Add(items);

                    foundInExceptionTable = true;
                    break;
                }
                else if (zipFileList.ContainsPartially(test1233)) // Match in zip with Different Hash found from ex table.
                {
                    FILE exists = zipFileList.Where(f => f.fileName == test1233.fileName).First();
                    object[] items = exRow.ItemArray;
                    Array.Resize(ref items, items.Length + 4);
                    items[items.Length - 1] = "N";
                    items[items.Length - 2] = exists.folderName;
                    items[items.Length - 3] = test1233.folderName;
                    items[items.Length - 4] = "Folder Override";
                    if (detectedFolderRenames.Rows.Count == 0 || !detectedFolderRenames.Rows.Contains(items[0]))
                        detectedFolderRenames.Rows.Add(items);

                    foundInExceptionTable = true;
                    break;
                }
            }
            else
                continue;
        }
        return foundInExceptionTable;
    }

更新:我还在为你做一个例子,但是在平均时间在这里是潜在的有用的信息:

UPDATE: I am still working on an example for you, but in the mean time here is potentially helpful information:

test1233' threw an exception of type 'System.NullReferenceException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2147467261
HelpLink: null
InnerException: null
Message: "Object reference not set to an instance of an object."
Source: null
StackTrace: null
TargetSite: null

Data:{System.Collections.ListDictionaryInternal} part对我来说有点有趣,我的课不使用任何字典列表。

The Data: {System.Collections.ListDictionaryInternal} part is a little interesting to me, my class does not use any dictionary lists.

更新#2:好的,我已经制作了一个可重复的步骤供他人尝试。在您的机器上,可能就好像Jon Skeet说的那样,这可能是我的调试环境设置,但请尝试让我知道。以下是重现步骤。

UPDATE #2: Ok, I have produced a reproducible sequence of steps for others to try. On your machines, it may be just fine, like Jon Skeet said, it might be my debug environment settings but please try and let me know. Here are the steps to reproduce.


  1. 打开控制台应用程序项目并复制下面的代码。

  2. 在此设置中断点:

  3. 首先运行代码过断点,它的工作原理! :D

  4. 然后再次运行代码,但这次在断点处停止,并将执行语句光标INGR从这里拖入if语句:

    到这里:

  1. Open console app project and copy paste code below.
  2. Set a break point here:
  3. First run code past break point, it works! :D
  4. Then run code again but this time STOP at the break point and DRAG the executing statement cursor INTO the if statement from here: to here:

在那里是!所以这个错误是由于我的测试方法造成的,但这是否有意义呢?这只是我在我的机器上吗?

There it is! So the error was caused from my method of testing, but does this make any sense or is this just me on my machine?

代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {
            FILECollection randomCollection = new FILECollection();
            // Fill with junk test data:
            for(int i = 0; i<10; i++)
            {
                FILE junkfile = new FILE() { fileName = i.ToString(), folderName = i.ToString(), fileHashDigest = new byte[1] };
                randomCollection.Add(junkfile);
            }

            if (true)
            {
                Console.WriteLine("testing this weird exception issue...");
                FILE test;
                test = new FILE();
                test.fileName = "3";
                test.folderName = "3";
                test.fileHashDigest = new byte[1];

                FILE exists = randomCollection.Where(f => f.fileName == test.fileName &&
                                              f.fileHashDigest.SequenceEqual(test.fileHashDigest)).First();
            }
        }
    }


    public class FILE
    {
        public FILE() { _fileName = "";}
        private string _fileName;
        public string fileName
        {

            get
            {
                    if (false)
                        return this._fileName.ToUpper();
                    else
                        return this._fileName;
            }
            set
            {

                    if (false)
                        this._fileName = value.ToUpper();
                    else
                        this._fileName = value;
            }
        }
        public string folderName { get; set; }
        public byte[] fileHashDigest { get; set; }
    }

    public class FILECollection : IEnumerable<FILE>, ICollection<FILE>
    {
        private HashSet<FILE> svgHash;
        private static List<FILE> PreallocationList;
        public string FileName = "N/A";

        /// <summary>
        /// Default Constructor, will not 
        /// preallocate memory.
        /// </summary>
        /// <param name="PreallocationSize"></param>
        public FILECollection()
        {
            this.svgHash = new HashSet<FILE>();
            this.svgHash.Clear();
        }

        /// <summary>
        /// Overload Constructor Preallocates
        /// memory to be used for the new 
        /// FILE Collection.
        /// </summary>
        public FILECollection(int PreallocationSize, string fileName = "N/A", int fileHashDigestSize = 32)
        {
            FileName = fileName;
            PreallocationList = new List<FILE>(PreallocationSize);
            for (int i = 0; i <= PreallocationSize; i++)
            {
                byte[] buffer = new byte[fileHashDigestSize];
                FILE preallocationSVG = new FILE()
                {
                    fileName = "",
                    folderName = "",
                    fileHashDigest = buffer
                };
                PreallocationList.Add(preallocationSVG);
            }
            this.svgHash = new HashSet<FILE>(PreallocationList);
            this.svgHash.Clear(); // Capacity remains unchanged until a call to TrimExcess is made.
        }

        /// <summary>
        /// Add an FILE file to 
        /// the FILE Collection.
        /// </summary>
        /// <param name="svg"></param>
        public void Add(FILE svg)
        {
            this.svgHash.Add(svg);
        }

        /// <summary>
        /// Removes all elements 
        /// from the FILE Collection
        /// </summary>
        public void Clear()
        {
            svgHash.Clear();
        }


        /// <summary>
        /// Determine if the FILE collection
        /// contains the EXACT FILE file, folder, 
        /// and byte[] sequence. This guarantees 
        /// that the collection contains the EXACT
        /// file you are looking for.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Contains(FILE item)
        {
            return svgHash.Any(f => f.fileHashDigest.SequenceEqual(item.fileHashDigest) &&
                                    f.fileName == item.fileName &&
                                    f.folderName == item.folderName);
        }

        /// <summary>
        /// Determine if the FILE collection 
        /// contains the same file and folder name, 
        /// byte[] sequence is not compared. The file and folder
        /// name may be the same but this does not guarantee the 
        /// file contents are exactly the same. Use Contains() instead.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool ContainsPartially(FILE item)
        {
            return svgHash.Any(f => f.fileName == item.fileName &&
                                    f.folderName == item.folderName);
        }

        /// <summary>
        /// Returns the total number
        /// of FILE files in the Collection.
        /// </summary>
        public int Count
        { get { return svgHash.Count(); } }

        public bool IsReadOnly
        { get { return true; } }

        public void CopyTo(FILE[] array, int arrayIndex)
        {
            svgHash.CopyTo(array, arrayIndex);
        }

        public bool Remove(FILE item)
        {
            return svgHash.Remove(item);
        }

        public IEnumerator<FILE> GetEnumerator()
        {
            return svgHash.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return svgHash.GetEnumerator();
        }
    }
}

我想我正在调试在一个非常错误的方式,或微软应该看看这个。这就像未来的代码是破坏当前的代码...这是不可能的!

I think either I am debugging in a terribly wrong way, or Microsoft should take a look at this. It's like future code is breaking current code...which is impossible!

推荐答案

我试图在控制台应用程序中执行代码,正在工作,可以给出更多的细节吗?关于设置初始化的答案在这里没有任何意义,因为您应该能够创建FILE的实例。一旦你尝试分配(设置)或请求(获取),那么你正在处理fileName属性。我不明白为什么在创建实例时收到异常。

I tried to execute the code in a console app and is working, can you give more details? Answers about the Settings initialization doesn't make sense here at this point because you should be able to create the instance of FILE. Once you try to assign(set) or request(get) then you are dealing with fileName property. I am not seeing why you get the exception when you create the instance.

 static void Main(string[] args)
        {
            FILE test1233;
            test1233 = new FILE(); // <---- Ex is not thrown here!?                           test1233.fileName = "";
            test1233.folderName = "";
            test1233.fileHashDigest = new byte[1];
        }

public class FILE
    {
        private string _fileName;
        public string fileName
        {

            get
            {
                if (YOUR SETTING CONDITION HERE)
                    return this._fileName.ToUpper();
                else
                    return this._fileName;
            }
            set
            {
                if (YOUR SETTING CONDITION HERE)
                    this._fileName = value.ToUpper();
                else
                    this._fileName = value;
            }
        }
        public string folderName { get; set; }
        public byte[] fileHashDigest { get; set; }
    }

查看打印屏幕上的光标

see the cursor on the print screen

这是我的调试配置

这篇关于c# - 没有运行YET的代码导致异常?这怎么可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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