“如果对象为空则为空,或者如果对象不为空则为 object.member"的快捷方式 [英] Shortcut for "null if object is null, or object.member if object is not null"
问题描述
我正在尝试编写一个通用的扩展方法,让我这样做:
I'm trying to write a generic extension method that let's me do this:
this.startDate = startDateXAttribute.NullOrPropertyOf<DateTime>(() =>
{
return DateTime.Parse(startDateXAttribute.Value);
});
NullOrPropertyOf()
将返回 null
如果它用于 null
对象(例如,如果 startDateXAttribute
是 null
),或者返回一个 Func
的结果,如果它不为 null.
NullOrPropertyOf()
would return null
if it's used on a null
object (e.g. if startDateXAttribute
was null
), or return the result of a Func
if it's not null.
这个扩展方法会是什么样子?
What would this extension method look like?
推荐答案
没有简短的形式;实现一个是一个相当频繁要求的功能.语法可能类似于:
There's no short form for that; implementing one is a fairly frequently requested feature. The syntax could be something like:
x = foo.?bar.?baz;
也就是说,如果 foo 或 foo.bar 为 null,则 x 为 null,如果它们都不为 null,则为 foo.bar.baz 的结果.
That is, x is null if foo or foo.bar are null, and the result of foo.bar.baz if none of them are null.
我们在 C# 4 中考虑过它,但它并没有使它靠近优先级列表的顶部.对于该语言的假设未来版本,我们会牢记这一点.
We considered it for C# 4 but it did not make it anywhere near the top of the priority list. We'll keep it in mind for hypothetical future versions of the language.
更新:C# 6 将具有此功能.有关设计注意事项的讨论,请参阅 http://roslyn.codeplex.com/discussions/540883.
UPDATE: C# 6 will have this feature. See http://roslyn.codeplex.com/discussions/540883 for a discussion of the design considerations.
这篇关于“如果对象为空则为空,或者如果对象不为空则为 object.member"的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!