可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Now again I am explaining one of my eagerness about Dictionary ! This question is popuped in my mind from answer of my previous question !!
Now the actual point is Can I convert Class into Dictionary ?
In Dictionary I want my class properties as KEY and value of particular property as VALUE
Suppose my class is
public class Location { public string city { get; set; } public string state { get; set; } public string country { get; set; }
Now suppose my data is
city = Delhi state = Delhi country = India
Now you can understand my point easily !
I want to make Dictionary ! That dictionary should be like
Dictionary dix = new Dictionary (); dix.add("property_name", "property_value");
I can get the value ! But how can i get property names (not value)?
What should I code to create it dynamic ! That should work for every class which I want ?
You can understand this question as
How can i get list of properties from particular class ?
回答1:
This is the recipe: 1 reflection, 1 LINQ-to-Objects!
someObject.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public) .ToDictionary(prop => prop.Name, prop => prop.GetValue(someObject, null))
Since I published this answer I've checked that many people found it useful. I invite everyone looking for this simple solution to check another Q&A where I generalized it into an extension method: Mapping object to dictionary and vice versa.
回答2:
Here a example with reflection without linq:
Location local = new Location(); local.city = "Lisbon"; local.country = "Portugal"; local.state = "None"; PropertyInfo[] infos = local.GetType().GetProperties(); Dictionary dix = new Dictionary (); foreach (PropertyInfo info in infos) { dix.Add(info.Name, info.GetValue(local, null).ToString()); } foreach (string key in dix.Keys) { Console.WriteLine("nameProperty: {0}; value: {1}", key, dix[key]); } Console.Read();
回答3:
Give this a try.
public static Dictionary ObjectToDictionary(object obj) { Dictionary ret = new Dictionary(); foreach (PropertyInfo prop in obj.GetType().GetProperties()) { string propName = prop.Name; var val = obj.GetType().GetProperty(propName).GetValue(obj, null); if (val != null) { ret.Add(propName, val.ToString()); } else { ret.Add(propName, null); } } return ret; }
回答4:
protected string getExamTimeBlock(object dataItem) { var dt = ((System.Collections.Specialized.StringDictionary)(dataItem)); if (SPContext.Current.Web.CurrencyLocaleID == 1033) return dt["en"]; else return dt["sv"]; }
回答5:
I would like to add an alternative to reflection, using JToken. You will need to check the benchmark difference between the two to see which has better performance.
var location = new Location() { City = "London" }; var locationToken = JToken.FromObject(location); var locationObject = locationObject.Value(); var locationPropertyList = locationObject.Properties() .Select(x => new KeyValuePair(x.Name, x.Value.ToString()));
Note this method is best for a flat class structure.