C# Exclamation Operator On Object

In c# what do the following code fragments do?

1)

if (!object)
{
  //code
}

2)

if (object)
{
  //code
}

Where object is an instance of a class, and definately not bool.

1) In java, trying the above code will make the compiler issue an error. Only boolean variables can be used as a Condition_Block. This works as expected.

2) In c++, if(!object){...} is used for null checks.

3) In c#, The compiler issues no error and happily compiles it. Google never mentions !operator used to objects. It only gives search results on bool values. Furthermore to add insult to the injury, it gives results of people talking about ? and ?? operators, which are operations that wont be available to unity developers for maybe 30-40 years. Only NET3.5 api is supported. If !exclamation operator works as in c++, why do people need ? and ??.

Edit: Full code.

using UnityEngine;

using System.Collections;

public class Foo : MonoBehaviour { void Start () { Foo a = new Foo(); if (a) Debug.Log("a"); if (!a) Debug.Log("b"); } }

it prints "b" on execute.


In C# there are three instances where if (!object) will compile:

  • If object is of type bool
  • If an implicit operator bool overload has been defined for the type of object .
  • If the ! operator has been overloaded for the type of object .
  • An example of overloading ! :

    class Test
    {
        public int Value;
    
        public static bool operator ! (Test item)
        {
            return item.Value != 0;
        }
    }
    

    And then:

    Test test = new Test();
    Console.WriteLine(!test); // Prints "False"
    
    test.Value = 1;
    Console.WriteLine(!test); // Prints "True"
    

    In C# there are two instances where if (object) will compile:

  • If object is of type bool .
  • If an implicit operator bool overload has been defined for the type of object .
  • An example of implicit operator bool :

    class Test
    {
        public int Value;
    
        public static implicit operator bool(Test item)
        {
            return item.Value != 0;
        }
    }
    

    And then:

    Test test = new Test();
    
    Console.WriteLine(!test); // Prints "True"
    
    if (test)
        Console.WriteLine("This is not printed");
    
    test.Value = 1;
    
    Console.WriteLine(!test); // Prints "False"
    
    if (test)
        Console.WriteLine("This is printed");
    
    链接地址: http://www.djcxy.com/p/13070.html

    上一篇: 在C ++中不敏感的字符串比较

    下一篇: 对象上的C#感叹号操作符