开发者

Neatest/most idiomatic way to rewrite this If in C#

I have this if-else statem开发者_Python百科ent which does what I want. What it's doing is pretty straightforward as you should be able to tell.

if (width != null && height != null)
{
    if (top != null && left != null)
    {
        ret.type = VMLDimensionType.full;
    }
    else
    {
        ret.type = VMLDimensionType.size;
    }
}
else
{
    if (top != null && left != null)
    {
        ret.type = VMLDimensionType.positon;
    }
    else
    {
        ret.type = VMLDimensionType.unset;
    }
}

The enum being referred to is:

private enum VMLDimensionType
{
    unset = 0,
    full = 1,
    size = 2,
    position = 3
}

It's so straightforward I'm sure there's a much more terse and more readable way to express this.

NB If it wasn't for the ridiculous 'one-brace per line' rule that VS imposes by default I probably wouldn't be so bothered. Eg in VB I could lose about 10 lines from this code block! (any thoughts on that as an aside?)


bool hasPosition = (top != null && left != null);
bool hasSize = (width != null && height != null);

if (hasSize)
{
    ret.type = hasPosition ? VMLDimensionType.full : VMLDimensionType.size;
}
else
{
    ret.type = hasPosition ? VMLDimensionType.positon : VMLDimensionType.unset;
}


One option would be to make VMLDimensionType a Flags enumeration:

[Flags]
enum VMLDimensionType
{
    Unset = 0,
    Size = 1,
    Position = 1 << 1,
    Full = Size | Position
}

And then:

ret.Type = VMLDimensionType.Unset;

if(width != null && height != null)
    ret.Type |= VMLDimensionType.Size;

if (top != null && left != null)
    ret.Type |= VMLDimensionType.Position;


How about this:

bool hasSize = width != null && height != null;
bool hasPosition = top != null && left != null;

if (hasSize && hasPosition)
{
    ret.type = VMLDimensionType.full;
}
else if (hasSize && !hasPosition)
{
    ret.type = VMLDimensionType.size;
}
else if (!hasSize && hasPosition)
{
    ret.type = VMLDimensionType.positon;
}
else
{
    ret.type = VMLDimensionType.unset;
}


I would like to extract GetDimensionType() method. And make it not so small, but more readable and self-descriptive.

private VMLDimensionType GetDimensionType()
{
    bool hasSize = width != null && height != null;
    bool hasPosition = top != null && left != null;

    if (hasSize && hasPosition)
        return VMLDimensionType.full;

    if (hasSize)
        return VMLDimensionType.size;

    if (hasPosition)
        return VMLDimensionType.positon;

    return VMLDimensionType.unset;
}

Usage:

ret.type = GetDimensionType();


What about this:

if(width != null && height != null)
    ret.type = top != null && left != null ? VMLDimensionType.full : VMLDimensionType.size;
else
    ret.type = top != null && left != null ? VMLDimensionType.positon : VMLDimensionType.unset;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜