我正在使用C#,ASP.NET,我使用UPS API跟踪来获取交付信息,在提出请求后,我找回了一个非常复杂且具有大量字段/属性的对象(trackResponse)或者嵌入其中的其他对象。
如何编程在该对象中搜索每个可能的值字段(string / int / double)?
基本上我想要一个像这样的方法:
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;
}
但上面的代码不起作用。请看一下。
答案 0 :(得分: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; }
}
}