如何深入搜索复杂对象中的每个字段



我使用的是C#,ASP.NET,我使用UPS API跟踪来获取递送信息,在提出请求时,我得到了一个非常复杂的对象(trackResponse),其中嵌入了很多字段/属性或其他对象。

如何编程以搜索该对象中的每个可能的值字段(字符串/整数/双精度)?

基本上我想要这样的方法:

public static bool FindValueInObject(object Input, object SearchValue)
    {
        Type MyType = Input.GetType();
        var props = typeof(MyType).GetProperties();
        foreach (PropertyInfo propertyInfo in props)
        {
            //Console.WriteLine(string.Format("Name: {0}  PropertyValue: {1}", propertyInfo.Name, propertyInfo.GetValue(mco, null)));
            Type ObjectType = propertyInfo.GetType();
            Type SearchType = SearchValue.GetType();
            object ObjectValue = propertyInfo.GetValue(Input, null);
            if (ObjectType == SearchType)
            {
                if(ObjectValue == SearchValue)
                {
                    return true;
                }
            }
            else
            {
                FindValueInObject(ObjectValue, SearchValue);
            }
        }
        return false;
    }

但是上面的代码不起作用。请看一看。

你去吧....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var mco = new MyComplexObject();
            mco.MyDate1 = DateTime.Now;
            mco.MyDate2 = DateTime.Now;
            mco.MyDate3 = DateTime.Now;
            mco.MyString1 = "String1";
            mco.MyString2 = "String1";
            mco.MyString3 = "String1";

            var props = typeof(MyComplexObject).GetProperties();
            foreach (PropertyInfo propertyInfo in props)
            {
                Console.WriteLine(string.Format("Name: {0}  PropertyValue: {1}", propertyInfo.Name, propertyInfo.GetValue(mco, null)));
            }
            Console.ReadLine();
        }
    }

    public class MyComplexObject
    {
        public string MyString1 { get; set; }
        public string MyString2 { get; set; }
        public string MyString3 { get; set; }
        public DateTime MyDate1 { get; set; }
        public DateTime MyDate2 { get; set; }
        public DateTime MyDate3 { get; set; }
    }
}

最新更新