سؤال

I have the following:

MovingDirection.UP;

and I want to use the ! operator as follows:

!MovingDirection.Up; // will give MovingDirection.Down

(it's an Enum)

I have tried:

public static MovingDirection operator !(MovingDirection f)
{
    return MovingDirection.DOWN;
}

... but I receive an error:

Parameter type of this unary operator must be the containing type

Any ideas?

هل كانت مفيدة؟

المحلول

No, you can't implement methods or operators on enums. You can create an extension method:

public static MovingDirection Reverse(this MovingDirection direction)
{
    // implement
}

Use like:

MovingDirection.Up.Reverse(); // will give MovingDirection.Down

Or you can use an enum-like class instead of an actual enum.

نصائح أخرى

You could do something like this:

private bool isMovingUp(MovingDirection value)
{
    if (value == MovingDirection.UP)
        return true;
     else
        return false;
}

and vice versa if you like.

Or use a bool as Guthwulf said.

Theoretically, this could be possible with extension methods, but unfortunatelly MS decided to not implement this feaure:

http://connect.microsoft.com/VisualStudio/feedback/details/168224/linq-cannot-implement-operator-overloading-as-extension-method

So it is either boolean if you have only up/down, or some methos IsUp(), IsDown(), ....

Not really an answer, but it works:

enum MovingDirection : byte { Up = 255, Down = 0 };

MovingDirection t1 = MovingDirection.Up;
MovingDirection t2 = (~t1);

You could do numeric or bitwise operations on the enum value, since enums are ints.

Note: This is not necessarily a good idea. Might not even be good. But shows another way to think of enums.

MovingDirection md = MovingDirection.*; // Some value
md += 1; // If it cannot be cast back to MovingDirection, then it is the default or first value aka 0 (like overflow)
(int)md & 1; // Or do some bitwise operands, like `~` to negate

edit: to show the enum and its int values

enum MovingDirection { UP = 0, DOWN = 1 }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top