加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#测试为null

发布时间:2020-12-15 19:37:19 所属栏目:百科 来源:网络整理
导读:我正在使用C#编写一个简单的程序来读取Active Directory并显示 Windows窗体程序中AD字段中保存的值. 如果某个属性不存在则程序崩溃,下面是我的代码,如何在不对每个属性执行try / catch的情况下捕获并转移到下一个字段? DirectoryEntry usr = new DirectoryE
我正在使用C#编写一个简单的程序来读取Active Directory并显示 Windows窗体程序中AD字段中保存的值.

如果某个属性不存在则程序崩溃,下面是我的代码,如何在不对每个属性执行try / catch的情况下捕获并转移到下一个字段?

DirectoryEntry usr = new DirectoryEntry("LDAP://" + domain,username,password);
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(sAMAccountName=" + GlobalClass.strUserName + ")";
searcher.CacheResults = false;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("telephoneNumber");

//program crashes here if telephoneNumber attribute doesn't exist.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();

解决方法

只检查usr.Properties [“telephoneNumber”]将无法正常工作.您必须检查实际值.发生错误的原因是因为您在Value上调用ToString(),该值为null.

无论输入到集合索引器中的属性名称如何,user.Properties将始终返回PropertyValueCollection.

var pony = usr.Properties["OMG_PONIES"]; // Will return a PropertyValueCollection
var value = pony.Value;                  // Will return null and not error

您需要检查值本身,通过null合并运算符的最佳方法:

textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value 
                            ?? "Not found").ToString();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读