I have constructed a generic method which “deserialiazes” an object in the following manner:
public class AClass
{
public int Id {get; set;}
public string Name {get;set;}
}
public class NestingClass
{
public string Address {get; set;}
List<AClass> Classes {get; set;}
}
the output if a list of keyvaluepair : NestingClass Value: none, AddressNestingClass value,
List1.Generic.Collections ClassesNestingClass none, IdAClassNestingClass value, NameAClassNestingClass value.
I manage to get the types of all , but with the values is a little harder because while using propertyInfo.GetValue() i cannot use always the object, e.g for the propertyInfos of a AClass the object (which is the type which forms the list of classes) the object should be of type AClass. Using “this” also does not work . I get the object doesn’t match the target object.
What I would need is some sort of mechanism of “slicing” through the object passed as a generic parameter and try to get the values in that manner.
The code is something like:
public List<KeyValuePair<string,string>> Process(object foo)
{
if (foo == null)
return new List<KeyValuePair<string,string>>();
var result = List<KeyValuePair<string,string>>();
var types = new Stack<Helper>();
types.Push(new Helper { Type = o.GetType(),Name = string.Empty, Value = string.Empty });
while (types.Count > 0)
{
Helper tHelper = types.Pop();
Type t = tHelper.Type;
result.Items.Add(new KeyValuePair { Key = tHelper.Name, Value = tHelper.Value });
if (t.IsValueType || t == typeof(string))
continue;
if (t.IsGenericType)
{
foreach (var arg in t.GetGenericArguments())
types.Push(new TypeHelper { Type = arg, Name = string.Empty });
continue;
}
foreach (var propertyInfo in t.GetProperties())
{
//here comes the issue
types.Push(new TypeHelper { Type = propertyInfo.PropertyType, Name = propertyInfo.Name + propertyInfo.DeclaringType.Name, Value= propertyInfo.GetValue(this,null).ToString() });
}
}
return result;
}
It seems you’re attempting to get property values from the types represented by your generic property’s types. This is not possible because you have to have an instance to have values to get. There is no instance associated with Type parameters so there are no property values to get.
Maybe if you can provide more context to what you’re trying to achieve, we can help you get there.