问题
With continutation to my earlier thread Using reflection read properties of an object containing array of another object. I am hoping to make this wonderful method from EvgK a generic method that can be used in multiple places in my code base.
public static void GetMyProperties(object obj)
{
List<MyPropertyInfo> oMyProp = new List<MyPropertyInfo>();
foreach (PropertyInfo pinfo in obj.GetType().GetProperties())
{
if (!Helper.IsCustomType(pinfo.PropertyType))
{
//add properties - name, value, type to the list
}
else
{
var getMethod = pinfo.GetGetMethod();
if (getMethod.ReturnType.IsArray)
{
var arrayObject = getMethod.Invoke(obj, null);
foreach (object element in (Array)arrayObject)
{
foreach (PropertyInfo arrayObjPinfo in element.GetType().GetProperties())
{
//add properties - name, value, type to the list
}
}
}
else
{
List<MyPropertyInfo> oTempMyProp = GetMyProperties(prop.GetValue(obj, null));
oMyProp.AddRange(oTempMyProp);
}
}
}
}
Again, I am trying to read a method passed by the user. I list the parameters, their properties and values. Once user provides the input values, I call the method dynamically to get the result object. The result is passed to GetMyProperties() method and the method list all the properties (to n level) - name, value and type.
Currently, I have two methods (definations below):
public List<MyPropertyInfo> GetMyProperties(Type type);
public List<MyPropertyInfo> GetMyProperties(object obj);
I use the first one to show the list of all the parameters of the selected method along with it's properties - name, value and type.
MethodInfo members = type.GetMethod(this.MethodName);
ParameterInfo[] parameters = members.GetParameters();
List<MyPropertyInfo> oMyProp = new List<MyPropertyInfo>();
foreach (var parameter in parameters)
{
oMyProp = GetMyProperties(parameter.ParameterType);
}
..creating the list of my properties so that user can input the params. I pass ParameterType and GetProperties method checks if it is custom type or not. If custom type then it calls itself with the type recursively to build a list that I bind to a grid for input.
The second method GetMyProperties(object obj) is used to list the return object. Since I don't know the return type of the selected method at compile time so using object type. I want to know if I can modify the second method somehow to use it for reading the parameters, properties and return types? Instead of having separate methods? Trying to reuse the code.
回答1:
I'm not sure I understand you correctly, but if you want to combine two methods in one, you can pass object in both cases, but check if object is Type or not and provide different logic for that cases:
public static void GetMyProperties(object obj)
{
if (obj is Type)
{
Type type = obj as Type;
... here is the first method logic ...
}
else
{
... here is the second method logic ...
}
}
来源:https://stackoverflow.com/questions/4923995/one-method-to-read-parameters-properties-and-return-types-at-runtime-using-c-sh