2016-10-11 5 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]; 

를, 그것은 예외가 발생합니다. 그러나 ... 코드에서이 변수에 대한 모든 참조를 제거하면 (디버그 모드에서는 아직 실행되지 않았지만 !!!) 아무런 예외도 발생하지 않습니다. 이 지구상에서 무슨 일이 벌어지고있는거야?

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 : 난 아직도 당신을 위해 예를 들어 작업입니다 만, 여기에 그 동안 잠재적으로 유용한 정보입니다 :에 refrence를 들어

, 여기가 전체의의 방법이다

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 : 좋아, 나는 다른 사람들이 시도 할 재현 가능한 일련의 단계를 만들어 냈다. 귀하의 컴퓨터에서 Jon Skeet이 말했듯이 디버그 환경 설정 일 수도 있지만 제게 알려주십시오. 여기에 재현 할 단계가 있습니다.

  1. 콘솔 앱 프로젝트를 열고 아래의 붙여 넣기 코드를 복사하십시오.
  2. 여기에 중단 점 설정 : enter image description here
  3. 첫 번째 실행 코드가 중단 점을 지나면 작동합니다! : D
  4. 그런 다음 다시 코드를 실행하지만, 중단 점에서이 시간 STOP 여기에서 if 문에 실행 문 커서를 드래그 enter image description here 여기에 :이 enter image description here

이입니다! 그래서 오류가 내 테스트 방법으로 인해 발생했는데, 어떤 의미가 있습니까? 아니면 내 컴퓨터에서이 오류입니까?

CODE :

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의 인스턴스를 생성 할 수 있어야하므로 Settings 초기화에 대한 대답은 여기서는 이해가되지 않습니다. 일단 할당 (설정) 또는 요청 (get)을 시도하면 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

참고로, 재현 가능한 단계와 코드를 추가했습니다. 지금은 코드가 불안정하게 실행될 때처럼 보이기 때문에이 코드를 무시 하겠지만, 작동하지만, 위의 디버그 단계를 따르면 예외가 발생합니다. 이상한. –

+0

디버그 구성이 다르기 때문에 어떤 예외도 발생시키지 않습니다.이 답변에 광산을 첨부하십시오. 다른 경우 확인하십시오 – Zinov

+0

이상한 일입니다. 나중에 제 3의 seprate 컴퓨터에 집에 도착 해 보겠습니다. 그것은 아주 잘 구성 디버그 수 있습니다. –

관련 문제