问题描述
我想编写一个通用的扩展方法,它可以让我做到这一点:
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()
将返回空
如果它在使用空
对象(例如,如果 startDateXAttribute
是空
),或返回函数功能,如果它不为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;
也就是说,x为空,如果富或foo.bar是空的,并且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将具备这一功能。请参见以设计考虑的讨论。
UPDATE: C# 6 will have this feature. See http://roslyn.codeplex.com/discussions/540883 for a discussion of the design considerations.
这篇关于快捷方式&QUOT;如果为null对象为空,或者如果对象不是null&QUOT object.member;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!