2013-05-06 53 views
-5

出於某種原因,這給了我一個「System.NullReferenceException:對象引用未設置爲對象的實例」錯誤。什麼會造成這種情況?C#System.NullReferenceException

public class Font 
{ 
    private PrivateFontCollection MyFonts = new PrivateFontCollection(); 
    public Font() 
    { 
     string resource = "zig_____"; 
     Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource); 
     System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);//this is the line that causes the error 
     byte[] fontdata = new byte[fontStream.Length]; 
     fontStream.Read(fontdata, 0, (int)fontStream.Length); 
     Marshal.Copy(fontdata, 0, data, (int)fontStream.Length); 
     MyFonts.AddMemoryFont(data, (int)fontStream.Length); 
     fontStream.Close(); 
     Marshal.FreeCoTaskMem(data); 
    } 
} 
+4

異常發生在哪條線上? – 2013-05-06 19:58:29

+0

我猜'流'是空的。似乎是唯一的可能性。 – 2013-05-06 19:59:41

+0

哎呀,對不起,我忘了標記行 – user2288056 2013-05-06 19:59:44

回答

2

看來你沒有正確加載字體流。確保你使用了正確的資源路徑,並確保資源實際存在。如果您不確定正確的路徑,可以調用GetManifestResourceNames()方法來查看程序集中存在的命名資源。

並且讓這是一個教訓:始終驗證您是否已正確加載資源;如果它應該在那裏,你可以優雅地處理它,而不是讓運行時爲你的程序炸彈。

+0

謝謝你是一個紳士和學者! – user2288056 2013-05-06 20:16:47

相關問題