首页 > 解决方案 > 构造函数返回指向现有实例的指针

问题描述

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

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

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

我想要实现的目标是可能的吗?我的思维过程是否存在设计问题?

标签: c#constructor

解决方案


你想做两个操作,一个是创建一个实例,另一个是返回一些值Default.MissingSprite。这在 C# 中是不可能的。


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

public SpriteState State { get; set;}

然后在创建时(就像你在你的例子中一样

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

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

最后,由用户State在使用前检查属性。

var mySprite = new Sprite();

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

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

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

推荐阅读