简体   繁体   中英

Class of Nullable objects

This question is more a curiosity then anything...

Say there is a class like:

public class Foo{
public int? x {get; set;}
public int? y {get; set;}
}

And somewhere in the project instances were created:

var foo1= new Foo
         {
           x= 1;
           y= 1;
         };

var foo2= new Foo
         {
           x= 1;
           y= 1;
         };

If for some reason they wanted to check to see if the equal each other and set them to NULL if they are and print to screen...

ex:

if(foo1.x == foo2.x)
   foo1.x = null;
if(foo1.y == foo2.y)
   foo1.y = null;

if(foo1 == null){
   Console.WriteLine("foo1 is NULL");
}else{
   Console.WriteLine("foo1 is not NULL");
}

Which would print?

The instance of foo1 exists, but all it's objects are set to NULL . I'm new to the concept of nullable types so this struck a curiosity in me! (My Visual Studio is on the fritz or I'd test myself)

I have two hands. If my two hands are empty, does that mean I do not exist?

An variable's null state does not depend on any of the properties of the instance it points at.

如您所说,foo本身仍然是一个实例化的对象,无论其成员数据的值如何,因此else语句都会输出。

You will have the else exucuted foo1 is not NULL , the object itself is not null, but the properties are.

you can set foo1 to null by foo1 = null

foo1 is still an instantiated object and so would not be null so Console.WriteLine("foo1 is not NULL"); would be executed.

If you really needed foo1 == null to return true if x and y are null then you could override the == operator and the Equals() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM