C# Об'єкт як bool

2075 / C# / Класи / Об'єкт як bool

 

class My {
  public int number;
  public static implicit operator bool(My obj)
  {
    if (obj.number > 0)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
}
 
static void Main(string[] args)
{
  My a = new My();
  a.number = 5;
  if (a)
  {
    Console.WriteLine("1 true");
  }
  else {
    Console.WriteLine("1 false");
  }

  a.number = -5;
  if (a)
  {
    Console.WriteLine("2 true");
  }
  else
  {
    Console.WriteLine("2 false");
  }
}

1 true
2 false

 

 


 

public static explicit operator bool(My obj){ }
if (Convert.ToBoolean(a)){ }