【发布时间】:2017-10-17 12:55:11
【问题描述】:
C# 有有用的Null Conditional Operator。 this answer 也有很好的解释。
我想知道当我的对象是动态/扩展对象时是否可以进行类似的检查。让我给你看一些代码:
鉴于这个类层次结构
public class ClsLevel1
{
public ClsLevel2 ClsLevel2 { get; set; }
public ClsLevel1()
{
this.ClsLevel2 = new ClsLevel2(); // You can comment this line to test
}
}
public class ClsLevel2
{
public ClsLevel3 ClsLevel3 { get; set; }
public ClsLevel2()
{
this.ClsLevel3 = new ClsLevel3();
}
}
public class ClsLevel3
{
// No child
public ClsLevel3()
{
}
}
如果我执行这种链式空值检查,它会起作用
ClsLevel1 levelRoot = new ClsLevel1();
if (levelRoot?.ClsLevel2?.ClsLevel3 != null)
{
// will enter here if you DO NOT comment the content of the ClsLevel1 constructor
}
else
{
// will enter here if you COMMENT the content of the ClsLevel1
}
现在,我将尝试通过动态 (ExpandoObjects) 重现此行为
dynamic dinRoot = new ExpandoObject();
dynamic DinLevel1 = new ExpandoObject();
dynamic DinLevel2 = new ExpandoObject();
dynamic DinLevel3 = new ExpandoObject();
dinRoot.DinLevel1 = DinLevel1;
dinRoot.DinLevel1.DinLevel2 = DinLevel2;
//dinRoot.DinLevel1.DinLevel2.DinLevel3 = DinLevel3; // You can comment this line to test
if (dinRoot?.DinLevel1?.DinLevel2?.DinLevel3 != null)
{
// Obviously it will raise an exception because the DinLevel3 does not exists, it is commented right now.
}
有没有办法用动力学模拟这种行为?我的意思是,检查一长串成员中的 null 吗?
【问题讨论】:
-
所以您想要
does this property exist支票而不是null支票? -
据我所知 - 没有办法做到这一点。
-
如果没有办法,那我们就必须建造它。
-
@mjwills 在我的情况下
does this property exists和null check是一回事
标签: c# .net dynamic expandoobject