开发者

Defining operators and testing for null

开发者 https://www.devze.com 2023-03-16 16:03 出处:网络
I have a class in C# where I define the operator ==. The method I have currently throws an object is null exception when testing the following

I have a class in C# where I define the operator ==. The method I have currently throws an object is null exception when testing the following

MyClass a = new MyClass(); if(a==null)....

This is frustrating because in the definition of the operator i can't ask if either parameter is null because it will just go into in开发者_开发知识库finite recursion.

How do I test to see if either parameter is null when defining the == operator.


Use object.ReferenceEquals:

if (object.ReferenceEquals(objA, null)) { ... }

Another option is to cast objA to object:

if ((object)objA == null) { ... }

You may want to consult these guidelines.


Use Object.ReferenceEquals(objA, null).

0

精彩评论

暂无评论...
验证码 换一张
取 消