1

我正在使用 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;
    }

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

4

1 回答 1

1

给你....

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

}
于 2013-09-27T04:43:28.803 回答