我正在尝试从静态方法初始化静态变量,但在初始化之后它仍然是null。我做错了什么?
class Database {
public static Database Connection = null;
public static void Create() {
Database.Connection = new Database();
if (Database.Connection == null) {
Console.WriteLine("Null");
}
}
public Database() {
Console.WriteLine("I got called");
}
}
我在这里遗漏了什么吗?调用方法后,Database.Connection为NULL,尽管已经调用了构造函数。
答案 0 :(得分:0)
class Database {
public static Database Connection = null;
static Database() {
Database.Connection = new Database();
if (Database.Connection == null) {
Console.WriteLine("Null");
}
}
public Database() {
Console.WriteLine("I got called");
}
}
你永远不会打电话给Create()
。如果您愿意,可以使用静态构造函数,如上所述。
答案 1 :(得分:0)
使用Static constructor初始化静态字段。
static Database()
{
Database.Connection = new Database();
}
答案 2 :(得分:0)
一个选项是使静态成员成为属性:
class Database
{
private static Database _connection = null;
public static Database Connection
{
get
{
if(null == _connection)
{
_connection = new Database();
}
return _connection;
}
}
}
如果您正在实现单例,那么您应该通过将其设为私有来隐藏构造函数。
private Database()
{
// This will only be called once, when the Connection
// property getter is first accessed and the private
// _connection field is still null. Note: when using
// the debugger, this may be before it is actually called
// explicitly from within your code!
Console.WriteLine("Database() constructor called");
}