开发者

Object property containing nothing as default in C#

开发者 https://www.devze.com 2023-01-22 12:33 出处:网络
In a class I have a property: public Move plannedMove; By default I would like it to contain nothing, so that I can test if it is set in my code in some some way similar to

In a class I have a property:

public Move plannedMove;

By default I would like it to contain nothing, so that I can test if it is set in my code in some some way similar to

if(!plannedMove)

Or something like that. I also want to be able to unset it so that it is blank to being empty. How can I do this?

Just in case I'm going about 开发者_开发知识库this totally wrong I will explain my original problem: my Player object needs to be able to have an optional precalculated move. In a method GetMove it needs to either return the precalculated move, or calculate one. How can I do this?

EDIT: Yikes, forgot to mention Move is a struct.


By default this instance wont be instantiated and will be null, therefore

if (plannedMove != null)
{
   // do something here
}

would be fine.


public Move plannedMove = null;

...    

if (plannedMove == null)
  plannedMove = ... // calculate new one

return plannedMove;


You test whether it's empty with:

if (plannedMove == null)

You set it to empty with:

plannedMove = null;

When you declare it with public Move plannedMove;, it's set to empty (null) by default.


set it to null in your constructor, or whenever you want it to have nothing:

this.plannedMove = null

then you can check it like:

if (this.plannedMove != null) ...


It seems that Move is a reference type. So your variable plannedMove is null by default.

if (plannedMove == null)
{
   // do something
} 

If it's a value type, check Nullable<T>

0

精彩评论

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