How can I get a list of elements and data types from an object array in C # with reflections?
Scenario: I have a method with an array parameter in my web service (asmx). Using reflection, I read the parameters of the method and view the properties. Here is my code:
Example: I have a webservice http: //localhost/services/myservice.asmx . It has a string GetServiceData(context mycontext) method string GetServiceData(context mycontext) . the context class has the following properties
- string name - Account[] accounts
The account, in turn, has
- string acct_name - string acct_address
I need to read the service dynamically to create the following output
<GetServiceData> <mycontext> <name>string</name> <accounts> <acct_name>string</acct_name> <acct_address>string</acct_address> </accounts> </mycontext> </GetServiceData>
To do this, I dynamically read MethodInfo and get all the parameters. Then I look through the parameters to get a list of all the properties and data types. If there is an array element in the properties, then I need to get all the elements of this array element.
Solution (thanks Ani)
foreach (MethodInfo method in methods) { sb.Append("<" + method.Name + ">"); ParametetInfo parameters = method.GetParameters(); foreach(ParameterInfo parameter in parameters) { sb.Append("<" + parameter.Name + ">"); if (IsCustomType(parameter.ParameterType)) { sb.Append(GetProperties(parameter.ParameterType)); } else { sb.Append(parameter.ParameterType.Name); } sb.Append("</" + parameter.Name + ">"); } sb.Append("</" + sMethodName + ">"); }
The GetProperties () method reads the type and actually iterates over each property and adds it to the string object. In this method, I want to check if the property is an array, then get all the elements and enter it.
public static string GetProperties(Type type) { StringBuilder sb = new StringBuilder(); foreach(PropertyInfo property in type.GetProperties()) { sb.Append("<" + property.Name + ">"); if (property.PropertyType.IsArray) { Type t = property.PropertyType.GetElementType(); sb.Append(GetProperties(t)); } else { sb.Append(property.PropertyType.name); } } sb.ToString(); }