c# - 构造函数返回指向现有实例的指针
问题描述
我想知道如何创建一个默认的类构造函数。我不想浪费资源,所以我只想让构造函数返回一个指向该类已经存在的实例的指针。
这是我想到的。显然,它不起作用,但我想遵循这段代码的逻辑。
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;
}
我想要实现的目标是可能的吗?我的思维过程是否存在设计问题?
解决方案
你想做两个操作,一个是创建一个实例,另一个是返回一些值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;
...
推荐阅读
- java - 测试 Spring Boot 应用程序,实体模拟
- php - 双向短信线程
- json - Terraform 0.12 AWS 资源,包含从变量构建的 JSON
- swift - 如何使用swift在悬停时显示滚动条?
- c# - 等待进程在表单加载事件中打开
- c - 在 avr c 中传递值错误地转换为 uint32_t
- python - ARX 型号是 Gekko
- ibm-cloud - IBM Watson Assistant:用于创建上下文实体的注释选项卡缺失
- php - 当我运行项目时,它显示控制器没有在 laravel 中退出,但它在控制器文件夹中我该怎么办?
- reactjs - 反应 SWR 获取未定义