![](/img/trans.png)
[英]C# elegant way to check if all shallow properties are null (or any property is not null)
[英]How to check with C#, in more elegant way, if only some of the object properties are null?
有很多方法可以做到這一點,也許更容易閱讀的一種方法是:
var o = new SomeObjectType // object is a keyword
{
Prop1 = null,
Prop2 = null,
Prop3 = 665
};
if(o is SomeObjectType { Prop1: null, Prop2: null } )
; // do stuff
把它放在一個非 Linq 的方式然后嘗試這樣的事情作為一個大綱:
int nullCount = 0
foreach (var property in object.GetType().GetProperties())
{
if (property.GetValue(object) == null) nullCount++;
}
if (nullCount == 1)
{
// do my first thing
}
else
{
// do my other thing
}
你可以實現它,
public bool hasMethod(object yourObject, string Prop)
{
return yourObject.GetType().GetMethod(Prop) != null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.