Let's say I have an object of unknown type
object obj
I can get it's base type with obj.GetType().BaseType
, but how do I proceed to convert obj
to this base type?
Context:
In my case, I'm writing a Serialize method which serliaizes any object to a string using reflection looking sort of like this
public static string Serialize(this object obj)
{
string _serialization;
foreach (field in obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public))
{
_serialization += field.value
}
return _serialization;
}
My problem in particular is that you can't get private fields from the base type with GetFields()
, so what I want to do is to convert field.value
to it's base type to be able to access those fields and recursively serialize all parent types of obj
.
So what I want to be able to do is basically
foreach (baseType in field.value.baseTypes)
{
serialization += field.value.ConvertToBaseType().Serialize()
}
All I could think of is Convert.ChangeType(object, Type)
but I get an exception saying object
needs to implement IConvertible
, and implementing IConvertible
in everything in my project is not an option. Also I suppose this method was intended for .net framework types and value types.
All code in this post is sample code used to recreate my situation as it is on a much larger scale and I can't just dump all that code here.
Edit:
This is not a duplicate of that post as I have an entirely different question even if my context is similar.
There simply isn't a direct solution to my problem so I'll close this.