处理数据,如果为 NULL 则继续
我必须处理许多数据项,例如
User u = NotMyObject.GetUser(100);
ProcessProperty(u.FirstName);
ProcessProperty(u.Surname);
ProcessProperty(u.Phone.Work);
ProcessProperty(u.Phone.Mobile);
...
ProcessProperty(u.Address.PostCode);
假设所有属性都作为字符串从 GetUser(...) 返回。我希望 ProcessProperty 所做的事情并不相关(例如,可能将值写入文件),但它看起来像:
private void ProcessProperty(string data) {
...
}
我的问题是 u.Phone & 。同样 u.Address 可能为 NULL 如何处理“User u”对象而不将每个 ProcessProperty(...) 调用放入 try/catch 块中?
如果问题的格式不好,我很抱歉,我仍在掌握发帖的技巧。
非常感谢。 N。
I have to process a number of items of data for example
User u = NotMyObject.GetUser(100);
ProcessProperty(u.FirstName);
ProcessProperty(u.Surname);
ProcessProperty(u.Phone.Work);
ProcessProperty(u.Phone.Mobile);
...
ProcessProperty(u.Address.PostCode);
Take it that all properties are returned from GetUser(...) as string. What ProcessProperty does is, I hope, not relevant (maybe write the value to a file, for example) but it would look like:
private void ProcessProperty(string data) {
...
}
My question is given that u.Phone & likewise u.Address may be NULL how can I process the "User u" object without putting each ProcessProperty(...) call in a try/catch block?
Apologies if the formatting of the question is no good, I'm still getting the hang of posting.
Many thanks. N.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可以尝试(也许它不优雅):
和
You could try (maybe it's not elegant):
and
如果您可以编辑 User 类,我将更改可以为 null 的属性上的 Set 代码,以将 NULL 转换为 String.Empty
If you can edit the User class I would change the Set code on the properties wich can be null to convert NULL to String.Empty
如果您可以控制 ProcessProperty 函数,那么您可以将其添加到函数中,
否则您可以编写此代码
if you have control of the ProcessProperty function then you can just add this inside the function
otherwise you can just write this
使用 lambda 表达式和扩展方法来创建一个 Maybe monad:
用法:
而不是使用长点链(如 u.Phone.Work.Whatever),如果第一个属性中的任何一个为 null,该长点链就会失败,该方法一旦看到 null 就会短路并返回 null。如果您必须在其他人的类中深入使用属性(而该人可能不是一个非常细心的程序员),那么这可以大大缩短您的代码(与使用 if 检查相反)。我认为在下面的文章中,作者使用了方法名称
With
而不是GetPropOrNull
,这样甚至可以进一步缩短它。参考:
Use lambda expressions and an extension method to make a maybe monad:
Usage:
Instead of using a long dot chain (like u.Phone.Work.Whatever) which fails if any of the first properties are null, this method short-circuits and returns null as soon as it sees a null. This can shorten your code by a great deal (as opposed to using if-checks) if you have to work with a property deep down in someone else's class who maybe isn't a very careful programmer. I think in the article below, the author uses the method name
With
instead ofGetPropOrNull
, so that even shortens it up further.Reference:
如果您无法更改ProcessProperty,请考虑包装它:
或者像 int.Parse() 与 int.TryParse() 一样:
If you CAN'T change ProcessProperty consider wrapping it:
or do it like int.Parse() vs. int.TryParse():