簡體   English   中英

如果只有某些對象屬性為空,如何以更優雅的方式檢查 C#?

[英]How to check with C#, in more elegant way, if only some of the object properties are null?

我有一個對象:

var object = new SomeObjectType()
{
   Prop1 = null,
   Prop2 = null,
   Prop3 = 665
}

假設Prop3永遠不會為null ,我如何驗證其余屬性是否為null ,或者其中之一不是?

現在我有:

if (object.Prop1 == null && object.Prop2 == null)
{
   //do stuff
}

但這非常不優雅,特別是如果我有孔隙特性要驗證。 而且我不知道如何使用空條件運算符?。 和 ?[]在我的情況下。

如何用 C# 做到這一點?

有很多方法可以做到這一點,也許更容易閱讀的一種方法是:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM