我可以将 Class 转换成 Dictionary
在字典中,我希望我的类属性作为键,并将特定属性的值作为值。
假设我的类(class)是
public class Location
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set;
}
现在假设我的数据是
city = Delhi
state = Delhi
country = India
现在你可以很容易地理解我的意思了!
我想做一个字典!该词典应该是这样的:
Dictionary<string,string> dix = new Dictionary<string,string> ();
dix.add("property_name", "property_value");
我可以取值!但是我怎样才能获得属性名称(不是值)呢?
我应该编写什么代码来创建它动态?这应该适用于我想要的每个类(class)。
你可以这样理解这个问题:
如何获取特定类的属性列表?
现在我再次解释我对词典的渴望之一!这个问题从我的previous question的回答中浮现在脑海中!!
最佳答案
这是秘诀:1 次反射,1 次 LINQ-to-Objects!
someObject.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => (string)prop.GetValue(someObject, null))
自从我发布这个答案后,我检查过很多人认为它有用。我邀请所有寻找这个简单解决方案的人查看另一个问答,我在其中将其概括为扩展方法:Mapping object to dictionary and vice versa
关于c# - 如何将类转换为 Dictionary<string,string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9210428/