将任何类转换为键值对 [英] Convert any class to a keyvaluepair

查看:64
本文介绍了将任何类转换为键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多(也许很多)这样的简单类

I have a number (maybe a lot) of classes that are simple like so

 public class ResultA
    {
        public DateTime Date { get; set; }
        public int Year { get; set; }
        public int Month { get; set; }
        public int Day { get; set; }
    }

 public class ResultB
    {
        public string Number { get; set; }
        public int Count { get; set; }
        public string Update { get; set; }
        public int Jewels{ get; set; }
    }

没有通用接口,但是它们没有简单的方法属性.

There is no common interface, but they don't have methods simply properties.

我希望能够将这样的任何类型转换为具有属性名称和值(如果已设置)的 KeyValuePair< string,string> .

I would like to be able to convert any type like this into a KeyValuePair<string,string> with the property name and the value if it is set.

反正有做这件可怕的事吗??

Is there anyway of doing this horrible thing!?

推荐答案

像这样使用反射:

[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

您还可以使用扩展方法:

You can also use a extension method:

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);
      }
    }
  }

这篇关于将任何类转换为键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆