Operator overload! with class Visibility c #

1

I am trying to overload the unit operator ! in C # , so that it receives as a parameter a Visibility . My goal is to reverse the visibility of a controller.

Example:

Button_Click(object sender, RoutedEventArgs e)
{
    ControlName.Visivility = !ControlName.Visivility;
}

For this, I've done the following code.

namespace Test
{
    //A namespace cannot directly contain a members such as fields or methods.
    public static Visibility operator !(Visibility visibility)
    {
        if (visibility == Visibility.Visible) return Visibility.Hidden;
        else return Visibility.Visible;
    }

    class VisivilityConverter
    {
        //The parameter of unary operator must be the containing type.
        public static Visibility operator !(Visibility visibility)
        {
            if (visibility == Visibility.Visible) return Visibility.Hidden;
            else return Visibility.Visible;
        }

    }
}

But I have these 2 errors:

  • Error 1: A namespace can not directly contain a members such as fields or methods.
  • Error 2: The parameter of unary operator must be the containing type.

If there is a way to do this, I hope someone can help me.

    
asked by Jesse R. Jose 22.08.2018 в 21:21
source

2 answers

2

The only way to overwrite the operators is by defining them in the same class and Visibility is an enum.

What you can do is create an extensor method that denies the value:

public static class VisibilityExtensions
{
   public static Visibility Negate(this Visibility v)
   {
     return v == Visibility.Visible ? Visiblity.Hidden : Visibility.Visible;
   }
}

Usage:

Button_Click(object sender, RoutedEventArgs e)
{
    ControlName.Visibility = ControlName.Visibility.Negate();
}

Or you can create an extender method that toggle property Visibility . If this Visible changes it to Hidden and vice versa:

public static class ControlExtensions
{
   public class void ToggleVisibility(this Control control)
   {
      contro.Visibility = control.Visibility == Visibility.Visible ? Visibility.Hidden : Visibility.Visible;
   }
}

Usage:

Button_Click(object sender, RoutedEventArgs e)
{
    ControlName.ToggleVisibility();
}
    
answered by 27.08.2018 / 17:58
source
2

I'll tell you, you're never going to be able to overload Visibility , since Visibility is a enum , and operator overloads apply only to clases and struct .

At the most you will be able to create a custom class which gives you this functionality, but what you are trying to do is not possible.

    
answered by 24.08.2018 в 04:52