.NET Fiddle
正如所述,计划在c# 6.0中实现?
运算符以在某种程度上方便这个过程。如果您不能等待,我建议使用lambda表达式和一个简单的帮助函数来解决这个问题。
public E NestedProperty<T,E>(T Parent, Func<T,E> Path, E IfNullOrEmpty = default(E))
{
try
{
return Path(Parent);
}
catch
{
return IfNullOrEmpty;
}
}
这可以在下面的演示中使用:int value = NestedProperty<First,int>(blank,f => f.Second.Third.id);
程序
public class Program
{
public void Main()
{
First blank = new First();
First populated = new First(true);
int value = NestedProperty<First,int>(blank,f => f.Second.Third.id);
Console.WriteLine(value);
value = NestedProperty<First,int>(populated,f => f.Second.Third.id);
Console.WriteLine(value);
value = NestedProperty<First,int>(blank,f => f.Second.Third.id,-1);
Console.WriteLine(value);
}
public E NestedProperty<T,E>(T Parent, Func<T,E> Path, E IfNullOrEmpty = default(E))
{
try
{
return Path(Parent);
}
catch
{
return IfNullOrEmpty;
}
}
}
简单的演示结构
public class First
{
public Second Second { get; set; }
public int id { get; set; }
public First(){}
public First(bool init)
{
this.id = 1;
this.Second = new Second();
}
}
public class Second
{
public Third Third { get; set; }
public int id { get; set; }
public Second()
{
this.id = 1;
this.Third = new Third();
}
}
public class Third
{
public int id { get; set; }
public Third()
{
this.id = 1;
}
}
if(msg.?Content.?AccountMarketMessage.?Account.?sObject == null) return;
- Lee