您还可以使用 SingleInstance Code 属性。它会自动为您做同样的事情!
[SingleInstance]
public class ExampleClass : Object {
public int prop { get; set; default = 42; }
public ExampleClass () {
// ...
}
}
int main (string[] args) {
var a = new ExampleClass (); // the two refs
var b = new ExampleClass (); // are the same
b.prop += 1;
assert (a.prop == b.prop);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,您不需要调用静态函数,例如instance()or get_instance()。只需通过创建一个对象new即可为您提供对单例的引用。