2016-10-11 3 views
-3

Так что я полностью в тупике. Я получаю сообщение об ошибке Object reference not set to an instance of an object., и я не уверен, почему.C# - Код, который НЕ РАБОТАЕТ, вызывает исключение? Как это вообще возможно?

У меня есть класс 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]; 

Как только переменная помещается в стек, он вызывает исключение. НО ... если я удалю все рефренсы этой переменной на код дальше вниз (КОТОРЫЙ НЕ ИСПОЛНИЛ В ДЕБЮГМОДЕ !!!), тогда никакое исключение не будет выбрано. Что здесь происходит?

Для refrence, здесь метод в полном комплекте:

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: Я до сих пор работает на примере для вас, но в то же время здесь потенциально полезная информация:

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} немного интересна мне, мой класс не использует списки словарей.

ОБНОВЛЕНИЕ # 2: Хорошо, я создал воспроизводимую последовательность шагов для других, чтобы попробовать. На ваших машинах это может быть очень хорошо, как сказал Джон Скит, это могут быть настройки среды отладки, но, пожалуйста, попробуйте и дайте мне знать. Вот шаги для воспроизведения.

  1. Открыть проект приложения консоли и скопировать код вставки ниже.
  2. Установить точку останова здесь: enter image description here
  3. Код первого запуска после точки останова, он работает! : D
  4. Затем запустите код еще раз, но на этот раз СТОП в точке разрыва и ТЯНИТЕ выполняющее заявление курсор INTO, если заявления здесь: enter image description here сюда: enter image description here

Там это! Таким образом, ошибка была вызвана моим методом тестирования, но имеет ли это смысл или это только я на моей машине?

КОД:

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

Я думаю, что либо я отладки в ужасно неправильно, или Microsoft должны смотреть на это. Это похоже на то, что будущий код нарушает текущий код ... что невозможно!

+0

всего пару нот: не называют класс что-то (например, файл ' '), который уже существует в рамках. Кроме того, если вы удалите все ссылки дальше вниз, я бы предположил, что компилятор вообще пропустит создание переменной. – DrewJordan

+8

Я сильно подозреваю, что есть что-то вялое с точки зрения вашей диагностики, возможно, экологически. Если бы вы могли воспроизвести это в [mcve], мы с большей вероятностью могли бы помочь. –

+0

Может быть, вам нужен конструктор с меньшим конструктором? – Hackerman

ответ

0

Я попытался выполнить код в консольном приложении и работает, можете ли вы дать более подробную информацию? Ответы об инициализации настроек здесь не имеют смысла, поскольку вы должны иметь возможность создать экземпляр FILE. После того, как вы попытаетесь присвоить (установить) или запросить (получить), вы имеете дело с свойством fileName. Я не вижу, почему вы получаете исключение при создании экземпляра.

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

см курсор на экране печати enter image description here

Вот моя конфигурация отладки

enter image description here

+0

FYI, я добавил воспроизводимые шаги и код. На данный момент я проигнорирую это, потому что похоже, что когда код выполняет невозмутимый, он работает, но после моих шагов отладки выше, он выдает исключение. странный. –

+0

не вызывает никаких исключений, может быть, ваша конфигурация отладки другая, я приложил бы мой ответ в этом ответе, пожалуйста, подтвердите, если они разные – Zinov

+0

Это странно, я попробую это позже, когда я вернусь домой на третьей машине seprate, это вполне может быть отладка конфигурации. –

Смежные вопросы