简体   繁体   English

可空对象的类别

[英]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... 如果出于某种原因,他们想检查彼此是否相等,然后将它们设置为NULL并打印到屏幕上...

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 . foo1的实例存在,但其所有对象均设置为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) (我的Visual Studio处于混乱状态,否则我会进行自我测试)

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. 您将拥有else被推导的foo1 is not NULL ,对象本身不为null,但属性为null。

you can set foo1 to null by foo1 = null 您可以通过foo1 = nullfoo1设置为foo1 = null

foo1 is still an instantiated object and so would not be null so Console.WriteLine("foo1 is not NULL"); foo1仍然是实例化的对象,因此不会为null,因此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. 如果确实需要foo1 == null来返回真(如果x和y为null),则可以覆盖==运算符和Equals()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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