空对象检查

时间:2010-03-25 19:39:23

标签: c#

有没有办法知道对象中的所有属性是否为空。我的对象表示来自数据库的字段,我想知道是否存在特定记录。 NULL似乎不起作用。

6 个答案:

答案 0 :(得分:5)

您是否尝试过检查 DBNull.Value

答案 1 :(得分:3)

您可以使用反射:

public static bool IsEmptyEntity<T>(T obj)
{
    foreach (var property in typeof(T).GetProperties())
        if (property.GetValue(obj, null) != null)
            return false;
    return true; 
}

用法:

    public class MyTestEntity
    {
        public string Str { get; set; }
        public int? Int { get; set; }
    }

MyTestEntity test = new MyTestEntity();
var empty = IsEmptyEntity(test); //returns true

答案 2 :(得分:0)

如果记录不存在,那你为什么要有一个对象代表它呢?

答案 3 :(得分:0)

如果你的object represents fields from database,那么它可能是一个集合。如果是这样,您很可能会使用myCollection.Any()之类的扩展方法来查看集合中是否有任何对象。那是你要的吗?

答案 4 :(得分:0)

许多语言使用名为IsEmpty的方法或属性进行此类检查。在对象的水合阶段设置一个布尔标志,指定对象是否为空。然后,您可以在其他地方使用属性或方法来检查空对象。

水化期间

bool _isEmpty = false;

if( prop1 is empty && prop2 is empty )
{
  _isEmpty = true;
}
else
{
  _isEmpty = false;
}

然后使用IsEmpty属性

IsEmpty
{
   get { return _isEmpty; }
}

答案 5 :(得分:0)

我发现只使用DBNull检查是不够的。也许不是最纯粹的方法,但作为字符串的临时检查似乎可以解决问题。像这样:

    if ((DBNull.Value != field) &&
        (!string.IsNullOrWhiteSpace(field.ToString())))