I am looking to get Fields / Properties of a particular object of unknown type. I have code that mostly works, but fails when attempting to expand members of a collection (a List, in this case).
Here is my code:
First the Class definitions:
public class Claim
{
public String icn;
public String subscriber;
public DateTime fdos;
public Double allowed;
public List<ClaimLine> claimLines;
public Claim(String icn, String subscriber, DateTime fdos, Double allowed)
{
this.icn = icn;
this.subscriber = subscriber;
this.fdos = fdos;
this.allowed = allowed;
this.claimLines = new List<ClaimLine>();
}
}
public class ClaimLine
{
public Int32 lineNumber;
public String procedure;
public String diagnosis;
public Double allowed;
public ClaimLine(Int32 lineNumber, String procedure, String diagnosis, Double allowed)
{
this.lineNumber = lineNumber;
this.procedure = procedure;
this.diagnosis = diagnosis;
this.allowed = allowed;
}
}
Now the code to build and the object and test the parser (Note: my objective is not to build xml, but it makes a good proof of concept because I can easily print or export it)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace TypeParser
{
class Program
{
static void Main(string[] args)
{
Claim claim = new Claim("12345678901234", "1234567890000", DateTime.Now, 0.0); //build main object
claim.claimLines.Add(new ClaimLine(1, "PROC1", "DIAG1", 10.55)); //add a couple of items to the list
claim.claimLines.Add(new ClaimLine(2, "PROC2", "DIAG2", 55.10));
String parsedType = parseType(claim, "");
Console.WriteLine(parsedType);
Console.ReadLine();
}
static String parseType(Object obj,String parsedType)
{
parsedType += "<" + obj.GetType().Name + ">\n";
foreach (FieldInfo fi in obj.GetType().GetFields())
{
if (fi.GetValue(obj) != null)
{
if (fi.FieldType.Name == "String" || fi.FieldType.IsPrimitive || fi.FieldType.Name == "DateTime")
{
parsedType += "<" + fi.Name + " type=" + fi.FieldType.Name + ">" + fi.GetValue(obj) + "</" + fi.Name + ">\n";
}
else
{
parsedType += parseType(fi.GetValue(obj), parsedType); //Property is not primitive so recurse
}
}
}
foreach (PropertyInfo pi in obj.GetType().GetProperties())
{
ParameterInfo[] paramInfo = pi.GetIndexParameters();
if (paramInfo.Length > 0)
{
//some code to implement processig list
}
else
{
if (pi.PropertyType.Name == "String" || pi.PropertyType.IsPrimitive || pi.PropertyType.Name == "DateTime")
{
parsedType += "<" + pi.Name + " type=" + pi.PropertyType.Name + ">" + pi.GetValue(obj, null) + "</" + pi.Name + ">\n";
}
else
{
//Property is not primitive so recurse
parsedType += parseType(pi.GetValue(obj, null), parsedType);
}
}
}
parsedType += "</" + obj.GetType().Name + ">\n";
return parsedType;
}
}
}
it is the section marked //some code to implement processig list that I am having difficulty with. I don't know how to get the values.
Aucun commentaire:
Enregistrer un commentaire