I am trying to create a utility function for serializing objects, Normally, serialization would happen as follows:
[Serializable]
public CoolCat : ISerializable
{
public string Name;
public void CoolCar(SerializationInfo info, StreamingContext context)
{
Name = (string)info.GetValue("Name", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", Name);
}
}
However, I want to be able to do the following:
[Serializable]
public CoolCat : ISerializable
{
public string Name;
public void CoolCar(SerializationInfo info, StreamingContext context)
{
Name = info.GetValue<string>(() => Name);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue<string>(() => Name);
}
}
I do this with the following two methods:
This one for deserializing the value:
public static T GetValue<T>(this SerializationInfo Source, Expression<Func<T>> MemberExpression)
{
string Name = ((MemberExpression)MemberExpression.Body).Member.Name;
return (T)Source.GetValue(Name, typeof(T));
}
and this one for serializing the value:
public static void AddValue<T>(this SerializationInfo Source, Expression<Func<T>> MemberExpression)
{
MemberExpression Body = MemberExpression.Body as MemberExpression;
if (Body == null)
{
UnaryExpression UnaryBody = MemberExpression.Body as UnaryExpression;
if (UnaryBody != null)
{
Body = UnaryBody.Operand as MemberExpression;
}
else
{
throw new ArgumentException("Expression is not a MemberExpression", "MemberExpression");
}
}
string Name = Body.Member.Name;
if (Body.Member is FieldInfo)
{
T Value = (T)((FieldInfo)Body.Member).GetValue(((ConstantExpression)Body.Expression).Value);
Source.AddValue(Name, Value, typeof(T));
}
else if (Body.Member is PropertyInfo)
{
T Value = (T)((PropertyInfo)Body.Member).GetValue(((ConstantExpression)Body.Expression, null);
Source.AddValue(Name, Value, typeof(T));
}
else
{
throw new ArgumentException("Expression must refer to only a Field or a Property", "MemberExpression");
}
}
I am getting an exception when trying to get the value from the Body.Member when it is a property (when it is a field, it works fine). How can I get this?
Other questions - 1) Are there any issues with the approach that I am taking? 2) Is there a better way perhaps to go about this whole thing? 3) When will the Body.Member be a FieldInfo and when will it be a PropertyInfo?
This is sort of an extension of my previous question Here