现在我再次解释我对词典的热切期待!我的回答是previous question !!
,这个问题在我脑海中浮现现在实际的点是我可以将类转换为字典吗?
在词典中,我希望我的类属性为 KEY ,特殊属性的值为 VALUE
假设我的班级是
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");
我可以获得价值!但是我如何获得属性名称(不值)?
我应该编码什么来动态创建它!这应该适用于我想要的每个课程吗?
您可以将此问题理解为
如何从特定类中获取属性列表?
答案 0 :(得分:130)
这是配方:1个反射,1个LINQ到对象!
someObject.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => prop.GetValue(someObject, null))
自从我发表这个答案后,我检查过很多人发现它很有用。我邀请所有寻找这个简单解决方案的人来检查另一个Q&amp; A,我将其推广到一个扩展方法:Mapping object to dictionary and vice versa。
答案 1 :(得分:15)
这是一个没有linq的反射示例:
Location local = new Location();
local.city = "Lisbon";
local.country = "Portugal";
local.state = "None";
PropertyInfo[] infos = local.GetType().GetProperties();
Dictionary<string,string> dix = new Dictionary<string,string> ();
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();
答案 2 :(得分:1)
我想使用JToken添加一个替代反射。您需要检查两者之间的基准差异,看看哪个具有更好的性能。
var location = new Location() { City = "London" };
var locationToken = JToken.FromObject(location);
var locationObject = locationObject.Value<JObject>();
var locationPropertyList = locationObject.Properties()
.Select(x => new KeyValuePair<string, string>(x.Name, x.Value.ToString()));
请注意,此方法最适用于平面类结构。
答案 3 :(得分:1)
public static Dictionary<string, object> ToDictionary(object model)
{
var serializedModel = JsonModelSerializer.Serialize(model);
return JsonModelSerializer.Deserialize<Dictionary<string, object>>(serializedModel);
}
我已经使用了上面的代码。尽可能简化,它无需反射即可工作,并且模型可以嵌套并且仍然有效。 (如果您使用的是 Json.net,请将您的代码更改为不使用 Newtonsoft)
答案 4 :(得分:0)
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 :(得分:0)
试一试。
public static Dictionary<string, object> ObjectToDictionary(object obj)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
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;
}
答案 6 :(得分:0)
送给某人的礼物只需要简单而扁平的Dictionary<String,String>
不需要层次结构或反序列化回像我这样的对象?
private static readonly IDictionary<string, string> SPECIAL_FILTER_DICT = new Dictionary<string, string>
{
{ nameof(YourEntityClass.ComplexAndCostProperty), "Some display text instead"},
{ nameof(YourEntityClass.Base64Image), ""},
//...
};
public static IDictionary<string, string> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
{
if (source == null)
return new Dictionary<string, string> {
{"",""}
};
return source.GetType().GetProperties(bindingAttr).ToDictionary
(
propInfo => propInfo.Name,
propInfo => propInfo.GetValue(source, null).GetSafeStringValue(propInfo.Name)
);
}
public static String GetSafeStringValue(this object obj, String fieldName)
{
if (obj == null)
return "";
if (obj is DateTime)
return GetStringValue((DateTime)obj);
// More specical convert...
if (SPECIAL_FILTER_DICT.ContainsKey(fieldName))
return SPECIAL_FILTER_DICT[fieldName];
// Override ToString() method if needs
return obj.ToString();
}
private static String GetStringValue(DateTime dateTime)
{
return dateTime.ToString("YOUR DATETIME FORMAT");
}
答案 7 :(得分:0)
我希望此扩展名对某人有用。
public static class Ext {
public static Dictionary<string, object> ToDict<T>(this T target)
=> target is null
? new Dictionary<string, object>()
: typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(
x => x.Name,
x => x.GetValue(target)
);
}