我有一些(可能很多)类很简单的类
KeyValuePair<string,string>
没有通用接口,但它们没有方法只是属性。
我希望能够将这样的任何类型转换为具有属性名称的{{1}}和设置的值。
无论如何都在做这件可怕的事情!?
答案 0 :(得分:7)
void Main()
{
GetValues(new ResultA
{
Date = DateTime.Now,
Year = 2000
}).Dump();
}
public IDictionary<string, string> GetValues(object obj)
{
return obj
.GetType()
.GetProperties()
.ToDictionary(p=>p.Name, p=> p.GetValue(obj).ToString());
}
public class ResultA
{
public DateTime Date { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
输出
Key Value
Date 10-Jun-15 14:48:11
Year 2000
Month 0
Day 0
答案 1 :(得分:6)
使用这样的反射:
[Test]
public void DoStuff() {
List<object> things = new List<object>() {
new ResultA(){Date = DateTime.Now, Month = 34}, new ResultB(){Count = 1, Jewels = 4, Number = "2", Update = "0"}
};
foreach (var thing in things) {
foreach (var property in thing.GetType().GetProperties()) {
Trace.WriteLine(property.Name + " " + property.GetValue(thing));
}
}
}
输出:
Date 10.06.2015 13:46:41
Year 0
Month 34
Day 0
Number 2
Count 1
Update 0
Jewels 4
您还可以使用扩展方法:
public static class ObjectExtensions {
public static List<KeyValuePair<string, object>> GetProperties(this object me) {
List<KeyValuePair<string, object>> result = new List<KeyValuePair<string, object>>();
foreach (var property in me.GetType().GetProperties()) {
result.Add(new KeyValuePair<string, object>(property.Name, property.GetValue(me)));
}
return result;
}
}
用法:
[Test]
public void DoItWithExtensionMethod() {
List<object> things = new List<object>() {
new ResultA(){Date = DateTime.Now, Month = 34}, new ResultB(){Count = 1, Jewels = 4, Number = "2", Update = "0"}
};
foreach (var thing in things) {
var properties = thing.GetProperties();
foreach (var property in properties) {
Trace.WriteLine(property.Key + " " + property.Value);
}
}
}