[英]C# Make a class return its instance without a function or variable
So I've been working with classes with single instances in Unity for a while and generally do this:因此,我在 Unity 中使用具有单个实例的类已经有一段时间了,通常这样做:
class PublicThings {
public static PublicThings I; // instance of this class
public int Score;
void Start { I = GetComponent<PublicThings>(); }
}
Usage: PublicThings.I.Score = 10;
用法:
PublicThings.I.Score = 10;
Which works pretty well.效果很好。 However, I've been curious as to whether or not it's possible to have the instance of the class be returned without having to type
.I
after the class.但是,我一直很好奇是否可以返回 class 的实例而无需在 class 之后键入
.I
。
So basically here's how it would look instead:所以基本上这就是它的外观:
PublicThings.Score = 10;
This question seems like it's relevent but I'm having trouble getting it to work. 这个问题似乎是相关的,但我无法让它发挥作用。
Is this possible?这可能吗? If so, how would it be done?
如果是这样,它会怎么做?
Three options to do what you are looking to do:三个选项来做你想做的事:
static
keyword in the PublicThings classstatic
关键字创建 static 属性/字段 Also it's worth noting that the Singleton Pattern doesn't necessarily solve your problem.另外值得注意的是,Singleton 模式不一定能解决您的问题。 You will still have to call something like
PublicThings.instance.Score
.你仍然需要调用
PublicThings.instance.Score
类的东西。
Hope this helps.希望这可以帮助。
Singleton pattern is the way to go. Singleton 模式是 go 的方式。
Also, with lazy instantiation.此外,使用惰性实例化。
public class PublicThings
{
private static PublicThings _instance;
// Your private constructor
private PublicThings() { }
public static PublicThings Instance
{
get
{
if (_instance == null)
{
// Construction of instance logic here
_instance = new PublicThings();
}
return _instance;
}
// No setter, read-only property
}
// Decide if Score is a read-only property or not.
public int Score { get; set; }
}
Whener the single instance of PublicThings
is required, it will be constructed and then stored.当需要
PublicThings
的单个实例时,它将被构造并存储。 A second access to the instance will provide the stored one.对实例的第二次访问将提供已存储的访问。
[Test]
public void WithTwoAccess_ToSingleInstance_MustBeTheSame()
{
var things1 = PublicThings.Instance;
var things2 = PublicThings.Instance;
Assert.AreSame(things2, things1);
// Asserts true
}
If your Score
property must be set once, just change que Instance
property to a method (commonly called GetInstance
) which expects the value of Score
.如果您的
Score
属性必须设置一次,只需将 que Instance
属性更改为需要Score
值的方法(通常称为GetInstance
)。
Hope it helps.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.