Why does SerializationInfo not have TryGetValue methods?

前端 未结 3 1723
暗喜
暗喜 2021-02-12 16:49

When implementing the ISerializable interface in C#, we provide a constructor which takes a SerializationInfo object, and then queries it with various

3条回答
  •  遥遥无期
    2021-02-12 17:03

    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 });
        }
    }
    

提交回复
热议问题