【问题标题】:How to check if property exists [duplicate]如何检查属性是否存在[重复]
【发布时间】:2014-04-15 15:01:40
【问题描述】:

我正在尝试从DirectoryEntry 读取属性。 不幸的是,并非所有记录都有employeeNumber 属性,所以我需要检查它是否存在。 我已经试过了:

a == one DirectoryEntry record
a.GetType().GetProperty("employeeNumber")==null //always returns true
String.IsNullOrWhiteSpace(a.Properties["employeeNumber"].ToString()) //exception

我还能尝试什么?

【问题讨论】:

  • 属性通常用 PascalCasing 编写,而不是 camelCasing。您的财产是如何定义的?
  • @OndrejJanacek 在我的案例中,属性是 camelCase
  • 你能试试bool doesExist = a.Properties.Contains("employeeNumber");吗?

标签: c#


【解决方案1】:

你可以这样试试:

OBJECT.GetType().GetProperty("PROPERTY") != null

所以在你的代码中它会是这样的:

var a = one DirectoryEntry record;
var pi = a.GetType().GetProperty("employeeNumber");
var value = pi.GetValue(a, null);

编辑:-

试试这个:

bool x = a.Properties.Contains("employeeNumber");

【讨论】:

  • 这与反思无关。这是关于 Active Directory。
  • GetValue 抛出 NullPointerException
  • @UlugbekUmirov:- 明白了:bool x = a.Properties.Contains("employeeNumber");这个呢?
  • @szpic:- 试试这个:- bool x = a.Properties.Contains("employeeNumber");
  • 谢谢回答,我会接受
【解决方案2】:

类似这样的:

a.Properties["employeeNumber"] == null || a.Properties["employeeNumber"].ToString().Length == 0

在您的情况下,a.Properties["employeeNumber"] 可以是 null,您会遇到异常,尝试将 null 转换为字符串。

【讨论】:

  • 即使没有employeeNumber,左侧总是返回false,因为属性没有Length属性
猜你喜欢
  • 2020-05-08
  • 2018-01-01
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
相关资源
最近更新 更多