在 C# 中检查对象是否为空

Checking if an object is null in C#(在 C# 中检查对象是否为空)
本文介绍了在 C# 中检查对象是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果对象为空,我想阻止对其进行进一步处理.

在下面的代码中,我检查对象是否为空:

if (!data.Equals(null))

if (data != null)

但是,我在 dataList.Add(data) 收到一个 NullReferenceException.如果对象为空,它甚至不应该进入 if 语句!

因此,我在问这是否是检查对象是否为空的正确方法:

public List数据列表;public bool AddData(ref 对象数据)布尔成功=假;尝试{//我也用过 "if (data != null)" 也没有用如果 (!data.Equals(null)){//此处发生NullReferenceException ...dataList.Add(data);成功 = doOtherStuff(data);}}捕获(例外 e){抛出新的异常(e.ToString());}返回成功;}如果这是检查对象是否为空的正确方法,我做错了什么(如何防止对对象进行进一步处理以避免 NullReferenceException)? 解决方案null 不是data,而是dataList.您需要创建一个public ListdataList = new List();更好:因为它是一个字段,所以将其设为私有.如果没有什么可以阻止您,请将其设置为 readonly.只是很好的做法.旁边检查无效性的正确方法是if(data != null).这种检查在引用类型中无处不在;甚至 Nullable<T> 覆盖了相等运算符,以便在检查 null 性时更方便地表达 nullable.HasValue.如果你执行 if(!data.Equals(null)) 那么你会得到一个 NullReferenceException 如果 data == null.这有点可笑,因为避免这种例外是首要目标.你也在这样做:catch(异常 e){抛出新的异常(e.ToString());}这绝对不好.我可以想象你把它放在那里只是为了你可以在方法内部时进入调试器,在这种情况下忽略这一段.否则,不要无缘无故地捕获异常.如果你这样做了,只需使用 throw; 重新抛出它们.I would like to prevent further processing on an object if it is null.

In the following code I check if the object is null by either:if (!data.Equals(null))
andif (data != null)
However, I receive a NullReferenceException at dataList.Add(data). If the object was null, it should never have even entered the if-statement!

Thus, I'm asking if this is proper way of checking if an object is null:public List<Object> dataList;
public  bool AddData(ref Object data)
    bool success = false;
    try
    {
        // I've also used "if (data != null)" which hasn't worked either
        if (!data.Equals(null))
        {
           //NullReferenceException occurs here ...
           dataList.Add(data);
           success = doOtherStuff(data);
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }
    return success;
}
If this is the proper way of checking if the object is null, what am I doing wrong (how can I prevent further processing on the object to avoid the NullReferenceException)? 解决方案 It's not data that is null, but dataList.

You need to create one withpublic List<Object> dataList = new List<Object>();
Even better: since it's a field, make it private. And if there's nothing preventing you, make it also readonly. Just good practice.

Aside

The correct way to check for nullity is if(data != null). This kind of check is ubiquitous for reference types; even Nullable<T> overrides the equality operator to be a more convenient way of expressing nullable.HasValue when checking for nullity.

If you do if(!data.Equals(null)) then you will get a NullReferenceException if data == null. Which is kind of comical since avoiding this exception was the goal in the first place.

You are also doing this:catch (Exception e)
{
    throw new Exception(e.ToString());
}
This is definitely not good. I can imagine that you put it there just so you can break into the debugger while still inside the method, in which case ignore this paragraph. Otherwise, don't catch exceptions for nothing. And if you do, rethrow them using just throw;.

                        这篇关于在 C# 中检查对象是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
                本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!
                
                
             
                  
                  上一篇:C#:应该将对象变量分配给 null 吗? 
                  下一篇:更简单的写空或空的方法? 
                  
                
              
            
          
          
          
            
              
                
                  相关文档推荐
                
                
                  
                    遍历属性时 ActiveDirectory 错误 0x8000500c
                  
                  ActiveDirectory error 0x8000500c when traversing properties(遍历属性时 ActiveDirectory 错误 0x8000500c)
                
                

                
                  
                    使用通配符按 samaccountname 搜索
                  
                  search by samaccountname with wildcards(使用通配符按 samaccountname 搜索)
                
                

                
                  
                    获取给定 UserPrincipal 的组列表
                  
                  Get the list of Groups for the given UserPrincipal(获取给定 UserPrincipal 的组列表)
                
                

                
                  
                    你能在 C# 中找到 Active Directory 用户的主要组吗?
                  
                  Can you find an Active Directory User#39;s Primary Group in C#?(你能在 C# 中找到 Active Directory 用户的主要组吗?)
                
                

                
                  
                    从 LDAP 查询用户组
                  
                  Query From LDAP for User Groups(从 LDAP 查询用户组)
                
                

                
                  
                    如何从 AD DirectoryEntry 获取 DOMAINUSER?
                  
                  How can I get DOMAINUSER from an AD DirectoryEntry?(如何从 AD DirectoryEntry 获取 DOMAINUSER?)
                
                

            
          
        
        
        
        
          
          
            
               
                栏目导航
                前端开发Java开发C/C++开发Python开发C#/.NET开发php开发移动开发数据库
                
              
            
          
          
          
          
            
              
                最新文章
                
                    • SqlConnection 如何管理IsolationLev...
                  

                    • SqlBulkCopy 是否自动启动事务?...
                  

                    • C#:将 null 传递给重载方法 - 调用哪...
                  

                    • “从服务器返回了一个推荐"从 C...
                  

                    • 自动将位图修剪到最小尺寸?...
                  

                    • 在 C# 中将 WriteableBitmap 转换为 ...
                  

                    • 无法在位图中设置调色板...
                  

                    • 在 .NET 中加载佳能 .CR2 文件...
                  

                    • 将位图设置为 MP3 的封面...
                  

                    • 在 C# 中将 32 位位图另存为 1 位 .b...
                  

                    • 用鼠标绘图会导致像素之间出现间隙...
                  

                    • C#:如何在使用位图时减少内存和 CPU ...
                  

              
            
          
          
          
          
            
              
                热门文章
                
                    • SqlConnection 如何管理IsolationLev...
                  

                    • SqlBulkCopy 是否自动启动事务?...
                  

                    • C#:将 null 传递给重载方法 - 调用哪...
                  

                    • “从服务器返回了一个推荐"从 C...
                  

                    • 自动将位图修剪到最小尺寸?...
                  

                    • 在 C# 中将 WriteableBitmap 转换为 ...
                  

                    • 无法在位图中设置调色板...
                  

                    • 在 .NET 中加载佳能 .CR2 文件...
                  

                    • 将位图设置为 MP3 的封面...
                  

                    • 在 C# 中将 32 位位图另存为 1 位 .b...
                  

                    • 用鼠标绘图会导致像素之间出现间隙...
                  

                    • C#:如何在使用位图时减少内存和 CPU ...
                  

              
            
          
          
          
          
            
              
                热门标签
                
        	织梦资讯网
         	
        	织梦模板
         	
        	dede
         	
        	外语学校
         	
        	织梦鬼故事
         	
        	竞价网站源码
         	
        	竞价培训网
         	
        	门户网站
         	
        	织梦二次开发
         	
        	织梦笑话网
         	
        	dedecms笑话网
         	
        	织梦源码
         	
        	网站建设
         	
        	搞笑图片
         	
        	织梦教程
         	
        	旅游网站源码
         	
        	织梦旅游网
         	
        	学校培训
         	
        	html5
         	
        	企业织梦源码
         	
        	医院源码
         	
        	后台样式
         	
        	移动营销页
         	
        	整形医院
         	
        	大学医院
         	
        	新手建站
         	
        	客服代码
         	
        	洗衣机维修
         	
        	企业网站
         	
        	淘宝客
         	
        	导航菜单
         	
        	教育网站
         	
        	学校源码
         	
        	装修网站
         	
        	装修模板
         	
        	美容整形
         	
        	女性健康
         	
        	妈妈网
         	
        	机械源码
         	
        	建站公司
         	
        	珠宝首饰
         	
        	苹果网站
         	
        	手机资讯
         	
        	美女图片
         	
        	织梦模版打包
         	
        	妇科源码
         	
        	安卓市场源码
         	
        	男性时尚网
         	
        	健康之家
         	
        	app应用网站
         	
        	笑话网站
         	
        	下载站
         	
        	美女图片网
         	
        	中医院网站
         	
        	家装网站源码
         	
        	QQ网站
         	
        	标牌网站
         	
        	魔兽世界网
         	
        	淘宝客源码
         	
        	YY网站源码
         	
        	别墅设计网站
         	
        	服装搭配网
         	
        	宝宝起名网
         	
        	站长网站
         	
        	婚庆网站
         	
        	脑科医院源码
         	
        	笑话源码
         	
        	肝胆医院
         	
        	意外怀孕源码
         	
        	工作室
         	

              
            
          
          
        
        
      
    
 
  
    
      
          
        网站首页 - 免责声明- 最新公告- 充值相关 - 网站地图
        
        Copyright © 2021-2022 深圳市沃梦达电子商务有限公司 All Rights Reserved. 粤ICP备14083021号