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

时间:2015-06-02 13:54:46

标签: c# .net 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 个答案:

答案 0 :(得分:0)

嗯,这里有一些问题。

  1. Passwords是静态和私有的原因是什么(如果类成员没有显式访问修饰符 - 它将是私有的)?由于它是私有的 - 您不能在PasswordPool类之外使用它。

  2. 您每次在Passwords方法中创建字典,但由于它是本地方法变量 - 在此方法之外它是无用的。此外,由于Passwords方法不会返回任何内容,并且不会使用此词典 - 它无用。

  3. ICollection<KeyValuePair<String, String>>你真的需要吗?为什么不简单地Dictionary<string, string>

  4. 如果我理解你的目标并且你正在尝试创建一些存储密码的类并需要一些静态方法来访问它们,那么你可以尝试这样的事情:

    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;
        }
    }
    

    此处词典是该类的私有成员,因此可以从PasswordPool的任何方法访问它,GetPassword是公共静态方法,允许通过用户名获取密码。