如何满足可以为null或为空的对象

时间:2012-12-13 21:39:42

标签: c# .net sql sql-server oop

我有一个对象,特别是以下内容:

table.ExtendedProperties["MS_Description"].Value

如果没有属性,Value为空。如果有属性,但该属性为空,则Value.toString()""

我想创建一个if-statement来迎合这两种可能性。这就是我到目前为止所做的:

if (table.ExtendedProperties["MS_Description"] == null ||
    table.ExtendedProperties["MS_Description"].Value.ToString().Equals(""))

问题是如果它为null,它仍在检查右侧的条件。

有什么想法吗?

5 个答案:

答案 0 :(得分:3)

你可以这样做:

if (table.ExtendedProperties["MS_Description"] == null || string.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value))

您的代码错误的原因是您不检查table.ExtendedProperties["MS_Description"].Value是否为空。

答案 1 :(得分:2)

因此Value不是字符串,那么你必须处理所有条件:

var description = table.ExtendedProperties["MS_Description"];
if (description == null ||
    description.Value == null || 
    description.Value.ToString().Equals(""))
    // no value

BTW 您的代码不太正确

if (table.ExtendedProperties["MS_Description"] == null ||
    table.ExtendedProperties["MS_Description"].Value.ToString().Equals(""))

您正在检查table.ExtendedProperties["MS_Description"]是否为空,而不是检查Value for null。确实如此。你走得更远,但是如果table.ExtendedProperties["MS_Description"].Value为空(你没有检查过,记得吗?),你将在应用ToString()时得到NullReferenceException。

答案 2 :(得分:1)

我不确定您是否引用了DataTable.ExtendedProperties属性或其他内容,但如果您是,则该属性返回System.Data.PropertyCollection,其继承自System.Collections.HashTable

这里讨论的大多数方法和属性(包括索引器(“Item”))都直接从HashTable继承,因此通常table.ExtendedProperties [key]可以返回任何对象,包括null。

请注意,您也可以调用DataTable.ExtendedProperties.ContainsKey(object key)来确定PropertyCollection是否包含特定密钥。

您是否知道在致电table.ExtendedProperties["MS_Description"].Value时要检索的对象类型?

如果是这样,可能会有其他属性可用于确定是否已设置属性等。

根据对象table.ExtendedProperties["MS_Description"]的类型,您甚至可以执行以下操作:

if ((table.ExtendedProperties["MS_Description"] ?? "").ToString().Length == 0) {
      .....
}

这将考虑到所有可能性:

  • 密钥不存在
  • 密钥存在,但值为null
  • 密钥存在且值为空

只要{Value}属性为null或为空时table.ExtendedProperties["MS_Decription"]对象返回“”。 所以关于返回的对象的更多信息可能会有很长的路要走!

答案 3 :(得分:0)

string.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value)

答案 4 :(得分:0)

看起来table.ExtendedProperties["MS_Description"]永远不会为空,你应该空检查Value属性而不是

string value = table.ExtendedProperties["MS_Description"].Value;
if (value == null || value.ToString().Equals(""))
// OR 
if (String.IsNullOrEmpty(value))

如果table.ExtendedProperties["MS_Description"]可以返回null,那么您需要

if (table.ExtendedProperties["MS_Description"] == null ||
    String.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value.ToString() ) 

由于table.ExtendedProperties["MS_Description"].Value可能会返回null,因此您需要

if (table.ExtendedProperties["MS_Description"] == null ||
    table.ExtendedProperties["MS_Description"].Value == null ||
    String.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value.ToString() )