Fazer uma PerguntaFazer uma Pergunta
 

RespondidoUsing properties with dictionary

  • sábado, 7 de novembro de 2009 19:39mupersan82 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Contém Código
    Hi there,

    I'm trying to retrieve an objects content based on a key in a dictionary, but don't know how to use the properties in combination with the dictionary. First of all, I create the dictionary and add 5 keys. Each keys value is an object of another class I've created: the Person class. Two parametres (username and password respectively) are passed and stored using properties. How do I retrieve one object and its content based on its key?

    Program class:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    
    namespace Lagerprojekt_final
    {
        class Program
        {
            static void Main(string[] args)
            {
                Dictionary<string, object> d = new Dictionary<string, object>();
                d.Add("kunde1", new Person("kunde1", "pass1"));
                d.Add("kunde2", new Person("kunde2", "pass2"));
                d.Add("kunde3", new Person("kunde3", "pass3"));
                d.Add("kunde4", new Person("kunde4", "pass4"));
                d.Add("admin", new Person("admin", "adminpass"));
    
                Person kunde1 = new Person();
    
                // See if Dictionary contains this string
                if (d.ContainsKey("kunde1")) // True
                {
    
                    string v = Convert.ToString(d["kunde1"]);
                    Console.WriteLine("Kunde1 Password: {0}", kunde1.Password);
                }
    
                Console.ReadLine();                                        
              
            }
        }
    }
    
    

    Person class:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    
    namespace Lagerprojekt_final
    {
        class Person
        {
            protected string brugernavn;
            protected string password;
    
    
            //Default constructor
            public Person()
            {
            }
    
            //Overload method which takes two parameters
            public Person(string brugernavn, string password)
            {
                this.brugernavn = brugernavn;
                this.password = password;
            }
    
            public string Brugernavn
            {
                set
                { brugernavn = value; }
                get
                { return brugernavn; }
    
            }
    
            public string Password
            {
                set
                { password = value; }
                get
                { return password; }
    
            }
    
        }
    }
    
    

    Regards,
    Anders

Respostas

  • sábado, 7 de novembro de 2009 21:20Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Respondido

    By using Person you can directly access Person object's properties. Because by passing Person type as generic you say the dictionary that field holds Person type.

    And if you type object Dictionary does not know whats the type and it can not cast it. Since object does not have property like password if you want to use properties of person you have to cast it to person manually.

    For example

    If you use object you can add Person for the first value, and string for the second, and int for the third. That means it holds multiple types and does not know what's the type. However if you use Person, you can only add person object. So it knows the value is person and you can access it's properties.

    • Marcado como Respostamupersan82 sábado, 7 de novembro de 2009 21:42
    •  

Todas as Respostas

  • sábado, 7 de novembro de 2009 19:41Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    Hi,

    Declare your dictionary like below. Use Person as value type instead of object.

    That might solve your problem.

    Dictionary<string, Person> d = new Dictionary<string, Person>();

    Then you can access password by d["kunde1"].Password
  • sábado, 7 de novembro de 2009 19:50mupersan82 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    Hi Tamer Oz,

    Thanks for your quick answer. However, I'm not sure if I understand it? Isn't it possible to do like I did with some small additions? If not, can you then elaborate a bit on your code?

    Thank you,
    Anders

  • sábado, 7 de novembro de 2009 19:53Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Resposta PropostaContém Código

    Hi,

    Change your code like below.

    namespace Lagerprojekt_final
    {
        class Program
        {
            static void Main(string[] args)
            {
                Dictionary<string, Person> d = new Dictionary<string, Person>();//this line changed
                d.Add("kunde1", new Person("kunde1", "pass1"));
                d.Add("kunde2", new Person("kunde2", "pass2"));
                d.Add("kunde3", new Person("kunde3", "pass3"));
                d.Add("kunde4", new Person("kunde4", "pass4"));
                d.Add("admin", new Person("admin", "adminpass"));
    
                Person kunde1 = new Person();
    
                // See if Dictionary contains this string
                if (d.ContainsKey("kunde1")) // True
                {
    
                    string v = Convert.ToString(d["kunde1"]);
                    Console.WriteLine("Kunde1 Password: {0}", d["kunde1"].Password);//this line changed
                }
    
                Console.ReadLine();                                        
              
            }
        }
    }
    
    
    • Sugerido como RespostaTamer OzMVPsábado, 7 de novembro de 2009 21:33
    •  
  • sábado, 7 de novembro de 2009 21:14mupersan82 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    Works like a charm, thanks!

    But I'm not sure why it works ;-) Can you explain the difference between using the Person object as a value type instead of an object?

    Regards,
    Anders
  • sábado, 7 de novembro de 2009 21:20Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Respondido

    By using Person you can directly access Person object's properties. Because by passing Person type as generic you say the dictionary that field holds Person type.

    And if you type object Dictionary does not know whats the type and it can not cast it. Since object does not have property like password if you want to use properties of person you have to cast it to person manually.

    For example

    If you use object you can add Person for the first value, and string for the second, and int for the third. That means it holds multiple types and does not know what's the type. However if you use Person, you can only add person object. So it knows the value is person and you can access it's properties.

    • Marcado como Respostamupersan82 sábado, 7 de novembro de 2009 21:42
    •  
  • sábado, 7 de novembro de 2009 21:30mupersan82 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    Aha, the missing link for me was generic types. When would it be an advantage to use object instead of generic type?
  • sábado, 7 de novembro de 2009 21:32Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    When if you are not sure about the type or you want to store different types. Example. If you use object you can add Person for the first value, and string for the second, and int for the third. That means it holds multiple types and does not know what's the type.
  • sábado, 7 de novembro de 2009 21:37mupersan82 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    I mean, it seems like generic types are a much better than object, so when would it be better to use object?
  • sábado, 7 de novembro de 2009 21:46Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    This is a sample to tell when using object is better.

    I don't prefeer to use object as generic.

    The advantages and disadvantages is similar to use object intstead a type.

    Here is a sample. You can't store all these types in a generic list other than object.

     

    List<object> o = new List<object>();

    o.Add(1);

    o.Add(

    "Sample");

    o.Add(

    Image.FromFile(""));