2014-02-20 161 views
0
public override bool Equals(object obj) 
{ 
    var par = obj as Parameter; 
    if (ParameterName == par.ParameterName) /* <=throws error at this code */ 
     return true; 
    else 
     return false; 

} 

我收到的時候我正在運行的代碼此錯誤:Object reference not set to an instance of an object「對象引用不設置到對象的實例。」錯誤

如何刪除在C#中的錯誤?

+0

@Amicable如果'par.ParameterName'是空的,不會拋出異常。 – dcastro

回答

5

原理ONE防禦性編程 - 總是檢查NULL

public override bool Equals(object obj) 
{ 
    // this statement CAN FAIL if your "obj" is *NOT* of type "Parameter" 
    var par = obj as Parameter; 

    // so therefore you MUST be ready to deal with a NULL value here! 
    if (par != null && ParameterName == par.ParameterName) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 

} 
1

您可以檢查是否parnull訪問ParameterName

public override bool Equals(object obj) 
{ 
    var par = obj as Parameter; 
    if (par!= null && ParameterName == par.ParameterName) /* <=throws error at this code */ 
     return true; 
    else 
     return false;  
} 
1

如何檢查,如果它是空首過嗎?

public override bool Equals(object obj) 
{ 
    var par = obj as Parameter; 
    if (par != null && ParameterName == par.ParameterName) /* <=throws error at this code */ 
     return true; 
    else 
     return false; 

} 
1

ther'es在你皈依一個問題Parametre你要檢查是否爲空

public override bool Equals(object obj) 
{ 
    var par = obj as Parameter; 
    if (par != null && ParameterName == par.ParameterName) 
     return true; 
    else 
     return false; 

} 
0

使用這種檢查par != null

public override bool Equals(object obj) 
{ 
    var par = obj as Parameter; 
    if (par != null && ParameterName == par.ParameterName) 
     return true; 
    else 
     return false; 

} 
相關問題