创建用于存储密码的字典 class

create dictionary class for storing Passwords

我正在尝试在 C# 中创建字典以存储密码。

你能帮帮我吗?我对此很陌生并且卡住了。我正在尝试创建

public class PasswordPool
{
    static void Passwords()
    {
        ICollection<KeyValuePair<String, String>> openWith =
            new Dictionary<String, String>();

        openWith.Add(new KeyValuePair<String, String>("User1", "Password"));
        openWith.Add(new KeyValuePair<String, String>("User2", "Password"));
        openWith.Add(new KeyValuePair<String, String>("User3", "Password"));

    }
}

我觉得这段代码不太好。你能告诉我缺少什么吗

嗯,这里有一些问题。

  1. Passwords 是静态和私有的原因是什么(如果 class 成员没有显式访问修饰符 - 它将是私有的)?因为它是私有的 - 你不能在 PasswordPool class.

  2. 之外使用它
  3. 你每次都在 Passwords 方法中创建你的字典,但因为它是本地方法变量 - 它在这个方法之外是无用的。此外,由于 Passwords 方法没有 returns 任何东西,并且对这本字典没有任何作用 - 它是无用的。

  4. ICollection<KeyValuePair<String, String>>你真的需要吗?为什么不直接 Dictionary<string, string>?

如果我正确理解了您的目标,并且您正在尝试创建一些 class 存储密码并需要一些静态方法来访问它们,那么您可以尝试这样的操作:

public class PasswordPool
{
    private static Dictionary<string, string> _Passwords;

    private static void InitPasswords()
    {
        _Passwords = new Dictionary<string, string>();

        _Passwords.Add("User1", "Password");
        _Passwords.Add("User2", "Password");
        _Passwords.Add("User3", "Password");
    }

    public static string GetPassword(string userName)
    {
        if (_Passwords == null)
            InitPasswords();

        string password;

        if (_Passwords.TryGetValue(userName, out password))
            return password;

        // handle case when password for specified userName not found
        // Throw some exception or just return null

        return null;
    }
}

这里的字典是 class 的私有成员,因此可以通过 PasswordPool 的任何方法访问它,而 GetPassword 是 public 允许通过用户名获取密码的静态方法.