构造函数返回指向现有实例的指针

时间:2019-06-03 18:20:26

标签: c# constructor

我想知道如何创建默认的类构造函数。我不想浪费资源,所以我只希望构造函数返回一个指向该类已经存在的实例的指针。

这就是我的想法。显然,它不起作用,但是我想遵循此代码的逻辑。

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;
}

我知道构造函数是无效的,所以我不能返回它们。

我不想只分配默认实例的值,因为那样会浪费内存,因为它只会创建默认实例的副本

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

我要实现的目标是可能的吗?我的思维过程中有任何设计问题吗?

1 个答案:

答案 0 :(得分:0)

您要执行两项操作,一项是创建实例,另一项是返回某个值Default.MissingSprite。在C#中是不可能的。


您应该做的是创建一个可处理状态并保存该值的属性,例如

public SpriteState State { get; set;}

然后创建时(就像您的示例中的

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

然后根据需要在其他构造函数中设置其他State

最后由用户决定使用前的State属性。

var mySprite = new Sprite();

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

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

   case Default.OkSprite:
      ...
   break;
  ...
相关问题