简体   繁体   中英

How to get object values within a dictionary<string,(object)>

For example I have a class named "Tree" with two private variables

    public class Tree()
    {
        private string name;
        private int age;

        public void Tree(string s, int x)
        {
         //simply make an object.
        }


    }

I create an object from another class making a Dictionary being

Dictionary<string, Tree> family = new Dictionary<string, Tree>;

the string would refer to Nickname, and Tree would contain the person whom it belongs to. (one person per nickname). Say the dictionary has a key of "Vats" and the Tree that belongs to "Vats" has name = Dan and age = 18. If I want to get name and age how would I go on about that because I'm sure I can't do:

"Vats" = nickN

string a = family.TryGetValue[nickN].name;
int x = family.TryGetValue[nickN].age;

any thoughts?

Tree tree = null;
if( family.TryGetValue( lastName, out tree ) )
{
    var fName = tree.Name;
    var age = tree.Age;
}

If you certainly know, that the item you want to access does exist in the dictionary, you can use direct access syntax with square brackets instead of using TryGetValue .

string a = family[nickN].name;
int x = family[nickN].age;

In order to access the private fields name and age from outside the Tree class, make them public or create public properties to access them like this:

public class Tree()
{
    private string name;
    private int age;

    public void Tree(string s, int x)
    {
        name = s;
        age = x;
    }

    public string Name{ get{ return name; }}
    public int Age{ get{ return age; }}
}

Then you can use:

string a = family[nickN].Name;
int x = family[nickN].Age;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM