【发布时间】:2014-07-16 22:44:15
【问题描述】:
过去几天我一直在阅读并尝试不同的方法来创建和使用我的一个类文件的单例实例,然后在 stackoverflow 上的整个程序生命周期中使用我需要的引用以及其他网站很少,并且发现有太多的意见、建议和示例让我有些困惑,尤其是在实际使用单例对象时。
我有一些功能,但我不认为这是最正确的方法,我可能会遗漏一步。
我的程序中有一个名为 clsRegistry 的简单类文件,它实现为单例。
public sealed class clsRegistry
{
//http://tech.pro/tutorial/625/csharp-tutorial-singleton-pattern
private static clsRegistry RegInstance;
private clsRegistry() { }
public static clsRegistry GetInstance()
{
lock (typeof(clsRegistry))
{
if (RegInstance == null)
{
RegInstance = new clsRegistry();
}
return RegInstance;
}
}
public string dataBase { get; set; }
public string userId { get; set; }
public string passWord { get; set; }
public void ReadKeys()
{
//http://stackoverflow.com/questions/1388787/information-in-registry
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Key1\Key2\Key3");
dataBase = key.GetValue("ADODataSource").ToString().Trim();
userId = key.GetValue("ServerUserID").ToString().Trim();
passWord = key.GetValue("ServerPassword").ToString().Trim();
}
} // end class definition
从 Main 方法调用时正确实现并调用类中的一个公共方法(ReadKeys)
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// create instance of registry class
clsRegistry regData = clsRegistry.GetInstance();
// call method
regData.ReadKeys();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new frmMain());
Application.Run(new frmLogin());
}
}
创建类的单例后,我加载了一个小的登录表单,我希望单例中的数据库名称显示在表单中,这是我的代码不够优雅的地方。
private void frmLogin_Load(object sender, EventArgs e)
{
// create a 'new' instance to the singleton?
clsRegistry regData = clsRegistry.GetInstance();
lblDataBase.Text = regData.dataBase;
}
我真的需要创建另一个对我的单例对象的引用以读取一些值(或稍后调用另一个方法)还是我在某个地方错过了一个步骤?我的操作假设是,一旦我将一个类的实例创建为单例并且它保留在同一个命名空间中,我就可以访问任何公共值或方法。没有?
作为参考,我正在使用 Visual Studio 2010 和 4.0 框架(是的,我是另一个经典的 VB 开发人员,终于跳槽了)
【问题讨论】:
-
我认为你做得对。仅仅因为您创建了单例对象的实例并不意味着您应该能够在范围之外使用对它的引用——它不是全局变量。如果您想在另一个类中使用该实例,则必须像在这里一样获得对它的引用。您不是在创建一个“新”单例,只是获取对现有单例的引用。至少这是我的理解。
-
您不是在“创建”一个新实例,只是获取单个实例的引用。
-
如果您最近几天都在阅读它,您一定偶然发现了Jon Skeets suggestion?在我看来,这是一个非常巧妙的实现
-
请务必阅读this question
-
你不应该公开
ReadKeys,你应该只是在构造函数中初始化数据。您的属性也不应该有二传手。最重要的是,您确定要将用户名和密码存储在注册表中吗,这听起来不安全。
标签: c#