有没有办法知道一个对象中的所有属性是否为空。我的对象代表数据库中的字段,我想知道特定记录是否存在。NULL似乎不起作用。
有没有办法知道一个对象中的所有属性是否为空。我的对象代表数据库中的字段,我想知道特定记录是否存在。NULL似乎不起作用。
你是否尝试过检查 DBNull.Value?
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
if ((DBNull.Value != field) &&
(!string.IsNullOrWhiteSpace(field.ToString())))
IsEmpty
的方法或属性进行此类检查。在对象集合的水化阶段,设置一个布尔标志以指定对象是否为空。然后,您可以简单地在其他地方使用该属性或方法来检查空对象。bool _isEmpty = false;
if( prop1 is empty && prop2 is empty )
{
_isEmpty = true;
}
else
{
_isEmpty = false;
}
然后使用IsEmpty
属性
IsEmpty
{
get { return _isEmpty; }
}
对象代表数据库中的字段
,那么它很可能是一个集合。如果是这样,你可以使用像myCollection.Any()
这样的扩展方法来查看集合中是否有任何对象。这是你所要问的吗?