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 :(得分: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 :(得分:1)
在访问par
之前,您可以检查null
是否不是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;
}
答案 2 :(得分: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;
}
答案 3 :(得分:1)
在转换为Parametre时出现问题,您必须检查是否为null
public override bool Equals(object obj)
{
var par = obj as Parameter;
if (par != null && ParameterName == par.ParameterName )
return true;
else
return false;
}
答案 4 :(得分:0)
用它来检查par != null
null
public override bool Equals(object obj)
{
var par = obj as Parameter;
if (par != null && ParameterName == par.ParameterName )
return true;
else
return false;
}