[英]How to check with C#, in more elegant way, if only some of the object properties are null?
I have an objekt:我有一个对象:
var object = new SomeObjectType()
{
Prop1 = null,
Prop2 = null,
Prop3 = 665
}
Assuming that Prop3
will be never null
, how can I verify if rest of the properties are null
, or one of them is not?假设
Prop3
永远不会为null
,我如何验证其余属性是否为null
,或者其中之一不是?
Right now I have:现在我有:
if (object.Prop1 == null && object.Prop2 == null)
{
//do stuff
}
But this is very not elegant, especially if I have pore properties to verify.但这非常不优雅,特别是如果我有孔隙特性要验证。 And I have no idea how could I use Null-conditional operators ?.
而且我不知道如何使用空条件运算符?。 and ?[] in my case.
和 ?[]在我的情况下。
How to do it with C#?如何用 C# 做到这一点?
There's many ways of doing this, perhaps one of the more easily readable is:有很多方法可以做到这一点,也许更容易阅读的一种方法是:
var o = new SomeObjectType // object is a keyword
{
Prop1 = null,
Prop2 = null,
Prop3 = 665
};
if(o is SomeObjectType { Prop1: null, Prop2: null } )
; // do stuff
Putting it in a non-Linq way then try something like this as an outline:把它放在一个非 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
}
You can achieve it with,你可以实现它,
public bool hasMethod(object yourObject, string Prop)
{
return yourObject.GetType().GetMethod(Prop) != null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.