在C#中,假设您希望从本例中的PropertyC中提取一个值,而ObjectA、PropertyA和PropertyB都可以为null。
ObjectA.PropertyA.PropertyB.PropertyC
如何用最少的代码安全地获得PropertyC?
现在我要查查:
if(ObjectA != null && ObjectA.PropertyA !=null && ObjectA.PropertyA.PropertyB != null)
{
// safely pull off the value
int value = objectA.PropertyA.PropertyB.PropertyC;
}做更像这样的事情(伪代码)是很好的。
int value = ObjectA.PropertyA.PropertyB ? ObjectA.PropertyA.PropertyB : defaultVal;甚至有可能用一个空聚结操作符进一步崩溃。
编辑最初我说我的第二个示例类似于js,但我将其更改为psuedo代码,因为正确地指出它在js中不能工作。
发布于 2014-11-07 02:03:32
在C# 6中,您可以使用空条件算子。所以最初的测试是:
int? value = objectA?.PropertyA?.PropertyB?.PropertyC;发布于 2014-04-02 10:56:53
短扩展法:
public static TResult IfNotNull<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator)
where TResult : class where TInput : class
{
if (o == null) return null;
return evaluator(o);
}使用
PropertyC value = ObjectA.IfNotNull(x => x.PropertyA).IfNotNull(x => x.PropertyB).IfNotNull(x => x.PropertyC);这种简单的扩展方法以及在http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/上可以找到的更多内容
编辑:
在使用它片刻之后,我认为这个方法的正确名称应该是IfNotNull(),而不是原来的With()。
发布于 2010-08-12 13:50:14
你能给你的班级添加一个方法吗?如果没有,您考虑过使用扩展方法吗?您可以为对象类型创建一个名为GetPropC()的扩展方法。
示例:
public static class MyExtensions
{
public static int GetPropC(this MyObjectType obj, int defaltValue)
{
if (obj != null && obj.PropertyA != null & obj.PropertyA.PropertyB != null)
return obj.PropertyA.PropertyB.PropertyC;
return defaltValue;
}
}用法:
int val = ObjectA.GetPropC(0); // will return PropC value, or 0 (defaltValue)顺便说一下,这假设您使用的是.NET 3或更高版本。
https://stackoverflow.com/questions/3468250
复制相似问题