我刚刚编写了一小段代码,令我震惊的是,在初始化将通过属性公开和使用的成员变量时,我不确定哪种初始化方法是最佳实践。从下面的两个示例中初始化我的成员变量的最佳方法是什么,更重要的是为什么?
示例 1:
private string m_connectionString = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ConnectionString;
private string m_providerName = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ProviderName;
public string ConnectionString
{
get { return m_connectionString; }
set { m_connectionString = value; }
}
public string ProviderName
{
get { return m_providerName; }
set { m_providerName = value; }
}
public EntityClusterRefreshServiceDatabaseWorker()
{
}
示例 2:
private string m_connectionString;
private string m_providerName;
public string ConnectionString
{
get { return m_connectionString; }
set { m_connectionString = value; }
}
public string ProviderName
{
get { return m_providerName; }
set { m_providerName = value; }
}
public EntityClusterRefreshServiceDatabaseWorker()
{
ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ConnectionString;
ProviderName = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ProviderName;
}
注意:假设我没有在静态上下文中使用这些变量。