The value is null, but does the check return otherwise?

EDIT: That explains everything! - Unity creates managed fake wrappers around your UnityEngine.Objects when you destroy them. This means that if you destroy UEObject, the C # shell may still be non-null. == is implemented in its own way, so if you destroy the check, UEObject == null will return true. This obviously does not work very well with generics.


It literally drives me crazy. I have this method right here:

public static void AssertNotNullAfterAssignment<T>(ref T value, Func<T> get, string msg) where T : class
{
    if (value == null)
        value = get();
    if (value == null)
        throw new NullReferenceException(msg);
}

I call it by reference null at the beginning:

AssertNotNullAfterAssignment(ref fovMeshFilter, GetComponent<MeshFilter>, "fovMeshFilter");

What really is crazy is that the check if (value == null)returns false! even if the value is null!

Here is a short video I made showing it.

, / , ( OnEnable), ( , OnEnable )

... , , . Equals ==, .

- , ?

: OnEnable, , :

private void OnEnable()
{
    //if (fovMeshFilter== null)
    //  fovMeshFilter= GetComponent<MeshFilter>();
    //if (fovMeshFilter== null)
    //  throw new NullReferenceException("fovMeshFilter");

    AssertNotNullAfterAssignment(ref fovMeshFilter, GetComponent<MeshFilter>, "fovMeshFilter");
}

uncommented lines, , , - --.

Edit1: ?

enter image description here

Edit2:

enter image description here

Edit3:

, . , , ! ! XD - .Equals ==. @Edin, == System.Object == - .Equals Equals. , , , '==' ?

+4
2

. null , . , , , . , DebuggerDisplay ToString() "null" , , .

[DebuggerDisplay("null")]
class A { }

a of a

var a = new A();

a|null , .

T, , . ToString() override, "null", : a|{null}.

EDIT:

Edit2, , . ==, , , true , , . , , T, . : #

, comparioson OnEnable(), .

, . .

:

class Person
{
  public string Name { get; set; }            

  public static bool operator ==(Person left, Person right)
  {
    // we consider Person null when it either has no Name or it is a null reference.
    if (object.ReferenceEquals(null, left) || left.Name == null)
      return object.ReferenceEquals(null, right);
    return left.Equals(right);
  }

  public static bool operator !=(Person left, Person right) { return !(left == right); }
  // Note that == and != operators should ideally be implemented in combination of Equals() override.
  // This is only for making an example for this question
}

private static bool IsNull<T>(T val)
{
  return val == null;
}

static void Main(string[] args)
{
  Person person = new Person();
  //this will display: person == null => True
  Console.WriteLine("person == null => {0}", person == null);
  //this will display: IsNull<Person>(person)=> False
  Console.WriteLine("IsNull<Person>(person)=> {0}", IsNull(person));
}
+4

vexe, , , , null, , . ? , . , null, .toString() .

, NULL. . ( .) - var foo = value.mesh; .

, /.

+3

Source: https://habr.com/ru/post/1542918/


All Articles