开发者

null and default values in page template

Very often i write code like:

<img c开发者_如何学编程lass="hasMenu" src="<%= (Model.Image==null)?Url.Content("~/Content/NoImage.jpg"):Model.Image.standard %>"
          alt="Main image" />

Is there any predefined function which could beauty this code? Something like: ValueOrDefault(Model.Image.standard,Url.Content("~/Content/NoImage.jpg"))


If what you meant was:

(Model.Image.standard==null)?Url.Content("~/Content/NoImage.jpg"):Model.Image.standard

then you simplify that using the null-coalescing operator:

Model.Image.standard ?? Url.Content("~/Content/NoImage.jpg")

If you meant what you said, you could write a method like this:

static class Obj
{
    public static T OrDefault<T>(Func<T> func, T def)
    {
        T result;
        try
        {
            result = func();
        }
        catch (NullReferenceException)
        {
            result = def;
        }
        return result;
    }
}

and use it like this:

Obj.OrDefault(() => Model.Image.standard, Url.Content("~/Content/NoImage.jpg"))


No, there is no way to check if a field is null and use its property in the same statement with basic operators part from the way you have already done it. There have been discussions about a "property null-coalescing operator", but I am unable to find it when searching the forum.

The way you coded it is the most efficient way and probably the way to go in terms of readability.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜