C#如何获取字典中对象的属性? [英] C# How to get the properties of an object in a dictionary?
问题描述
我有问题,我不知道如何获取字典中列出的对象的属性。
例如
I have the problem, that I don't know how to get the properties of an object that is listed in a dictionary.
E.g.
public class Person
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
在另一个类中,我创建了一些名为Peter,Paul和Marie的Person对象,并将它们保存在这样的字典:
字典<字符串,> persons = new Dictionary< string,>();
In another class I created some objects from "Person" with the names Peter, Paul and Marie and saved them in a dictionary like this:
Dictionary<string,> persons = new Dictionary<string,>();
persons.Add("Person1", new Person{ Name = Peter });
persons.Add("Person2", new Person{ Name = Paul });
persons.Add("Person3", new Person{ Name = marie });
现在我想获取属性Name的值与Person1键配对的对象。
如何解决这个问题?
编辑:
它只是在我脑海中点击,我找到了适用于我的情况的解决方案:
Now I want to get the value of the property "Name" from the object which is paired with the key "Person1".
How to solve this problem??
EDIT:
It just made "click" in my head and I found the solution which will work for my situation:
Person personName;
persons.TryGetVale("Person1", out personName);
string wantedName = personName.Name;
很抱歉,我打开了这个问题......我不认为我在问这个问题几分钟后就得到了解决方案......
Sorry that I opened this question... I did not think that I get the solution just a few minutes later than I asked this question...
推荐答案
从字典中读取的常用方法是
The usual way to read from a dictionary would be
string watsername = persons["Person3"].Name;
正如您已经通过使用 TryGetValue()来暗示
,你应该正确处理字典中可能存在 Person3
的可能性。
As you already hinting by your use of TryGetValue()
, You should properly handle the possibility that Person3
may or may not exist in the dictionary.
这篇关于C#如何获取字典中对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!