When implementing the ISerializable
interface in C#, we provide a constructor which takes a SerializationInfo
object, and then queries it with various
Well no one answered 'why', but I'm guessing that's addressed to MS..
My implementation for anyone in need:
public static class SerializationInfoExtensions
{
public static bool TryGetValue<T>(this SerializationInfo serializationInfo, string name, out T value)
{
try
{
value = (T) serializationInfo.GetValue(name, typeof(T));
return true;
}
catch (SerializationException)
{
value = default(T);
return false;
}
}
public static T GetValueOrDefault<T>(this SerializationInfo serializationInfo, string name, Lazy<T> defaultValue)
{
try
{
return (T) serializationInfo.GetValue(name, typeof(T));
}
catch (SerializationException)
{
return defaultValue.Value;
}
}
}
In addition to the enumerating solution, there is an internal method SerializationInfo.GetValueNoThrow()
according to the Reference Source.
You can e.g. make an extension method like this and avoid the exception overhead:
static class SerializationInfoExtensions
{
private static MethodInfo _GetValueNoThrow =
typeof(SerializationInfo).GetMethod("GetValueNoThrow",
BindingFlags.Instance | BindingFlags.NonPublic);
public static Object GetOptValue(this SerializationInfo info, String name, Type type)
{
return _GetValueNoThrow.Invoke(info, new object[] { name, type });
}
}
You can iterate over the available fields and use switch
, though...
foreach(SerializationEntry entry in info) {
switch(entry.Name) {
...
}
}
Or you could use protobuf-net ;-p