2011-10-20 25 views
0

當我嘗試將從Matrix類型派生的類型的屬性從MathNet library與nullptr進行比較時,發生了奇怪的NullReferenceException。使用Mathnet測試(m == nullptr)時的NullReferenceException矩陣類型

我想寫一個類轉換的C++/CLI類庫,它來自MathNet :: Numerics :: LinearAlgebra :: Matrix,它應該在三維空間中以齊次座標表示4x4矩陣中的位置。因爲我想能夠設置相對於其他頭寸的頭寸,我有一個屬性Transformation^ parent。 通過if(parent == nullptr){ ... }我想測試,如果當前的轉型有父,但我得到這個例外在符合if(parent == nullptr)

An unhandled exception of type 'System.NullReferenceException' occurred in MathNet.Iridium.dll 
Additional information: Object reference not set to an instance of an object. 

我的轉型類看起來是這樣的:

/// Transformation.h 
using namespace MathNet::Numerics::LinearAlgebra; 
using namespace System; 
ref class Transformation : Matrix 
//ref class Transformation : A 
{ 
public: 
    Transformation(void); 
    Transformation^ parent; 
    void DoSomething(); 
}; 


/// Transformation.cpp 
#include "StdAfx.h" 
#include "Transformation.h" 
Transformation::Transformation(void) : Matrix(4,4) 
{ 
} 
void Transformation::DoSomething() 
{ 
    if(parent == nullptr) // Produces NullReferenceException 
    { 
     Console::WriteLine("parent is nullptr"); 
    } 
    Matrix^ m; 
    if(m == nullptr)  // Produces NullReferenceException, too 
    { 
     Console::WriteLine("m is nullptr"); 
    } 
} 

比較任何Matrix類型的變量,實際上是null,到nullptr似乎會拋出這個異常。如果正確初始化,沒有例外的,所以這個工作得很好:

Matrix^ m = gcnew Matrix(4,4); 
if(m == nullptr)  // works fine 
{ 
    Console::WriteLine(""); 
} 

當汲取轉型,從一個不同的類,而不是ref class Transformation : Aref class Transformation : Matrix,一切正常了。

現在它變得非常奇怪。我想在C#應用程序中使用我的類庫。在轉換t上調用t.DoSomething()將引發NullReferenceException。但是,如果我直接包含空值測試在我的C#應用​​程序,它的工作原理:

Transformation t = new Transformation(); 
// t.DoSomething();  // Throws NullReferenceException 
if (t.parent == null) // OK! 
{ 
    Console.WriteLine("parent is null"); 
} 

做同樣的在C++/CLI應用程序再次拋出NullReferenceException異常:

Transformation^ t = gcnew Transformation(); 
// t->DoSomething();  // Throws NullReferenceException 
if(t->parent == nullptr) // Throws NullReferenceException 
{ 
    Console::WriteLine("parent is nullptr"); 
} 

任何建議,其中本可能來自?我真的很疑惑...

我使用MathNet.Idirium Library, Version 2008.8.16.470

+0

這通常表示* this *爲空。雖然不符合你的測試代碼。也許是版本問題。 –

+0

如果這個(在這個上下文中的意思是t)是空的,我不能調用DoSomething()或者我錯了嗎?異常僅在DoSomething()內引發,而不是在調用時引發。 – richn

+0

對於C++/CLI來說它不同,它不會生成代碼來確保* this *不像C#那樣是空的。當你嘗試訪問一個班級成員時,它會炸彈。可能很難診斷。但我同意你的測試使得這不太可能是這個問題的真正原因。在調試器中查看* this *以獲取任何提示。 –

回答

1

它可能在C#中至少==操作中拋出一個空引用的方式來實現。

你可以嘗試調用Object :: ReferenceEquals(obj,null)並查看它是否有效?

+0

謝謝安迪,與'if(Object :: ReferenceEquals(parent,nullptr))'相比,沒有排斥! 因此,這是Matrix實施中的一個微妙之處? – richn

+0

@richn:如果通過'微妙'你的意思是'錯誤',那麼是的。 – ildjarn

+0

@ildjarn哈哈;-)我只是想知道我是否可以「看見」何時使用'ReferenceEquals()'和何時'=='。 – richn