简体   繁体   中英

Constructor return pointer to existing instance

I'm wondering how to create a default class constructor. I do not want to waste resources, so I just want the constructor to return a pointer to an already existing instance of the class.

This is what I thought of. Obviously, it doesn't work, but I want to follow this code's logic.

public Sprite()
{
  return Default.MissingSprite;
}

public Sprite(Texture2D texture, SpriteDrawMode drawMode)
{
  if (drawMode != SpriteDrawMode.Sliced) throw new ArgumentException("...");
  this.texture = texture;
  this.drawMode = drawMode;
  this.sliceFraction = Default.SpriteSliceFraction;
}

public Sprite(Texture2D texture, SpriteDrawMode drawMode, float sliceFraction)
{
  this.texture = texture;
  this.drawMode = drawMode;
  this.sliceFraction = sliceFraction;
}

I know constructors are void, so I can't return in them.

I do NOT want to just assign the values of the default instance, as that would waste memory, since it would just create a duplicate of the default instance

//This is what I do NOT want
public Sprite()
{
  this.texture = Default.MissingSprite.texture;
  this.drawMode = Default.MissingSprite.drawMode;
  this.sliceFraction = Default.MissingSprite.sliceFraction;
}

Is what I'm trying to achieve possible? Are there any design problems with my thought process?

You want to do two operations, one is to create an instance and the other is to return some value Default.MissingSprite . This is not possible in C#.


What you should do is create a property which addresses the state and holds that value such as

public SpriteState State { get; set;}

Then upon creation ( like you have in your example )

public Sprite()
{
   State = Default.MissingSprite;
} 

Then set other State s in the other constructors as appropriate.

Finally it is up to the user to check the State property before usage.

var mySprite = new Sprite();

// Some code which could change the State...

switch (mySprite.State)
{
   case Default.MissingSprite:
      ...
   break;

   case Default.OkSprite:
      ...
   break;
  ...

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