Пример #1
0
        protected DictionarySerializer(EncryptAttribute encryptAttribute, IXmlSerializerOptions options)
        {
            // ReSharper disable DoNotCallOverridableMethodsInConstructor

            _encryptAttribute =
                encryptAttribute
                ?? KeyType.GetCustomAttribute <EncryptAttribute>()
                ?? ValueType.GetCustomAttribute <EncryptAttribute>();

            _options         = options;
            _keySerializer   = XmlSerializerFactory.Instance.GetSerializer(KeyType, null, _options.WithRootElementName("Key").WithRedactAttribute(null));
            _valueSerializer = XmlSerializerFactory.Instance.GetSerializer(ValueType, null, _options.WithRootElementName("Value"));

            if (DictionaryType.IsReadOnlyDictionary())
            {
                _createDictionary   = DefaultDictionaryType.CreateDefaultConstructorFunc <object>();
                _finalizeDictionary = FinalizeCollectionIntoReadOnlyDictionary;
            }
            else if (DictionaryType.IsInterface || DictionaryType.IsAbstract)
            {
                if (DictionaryType.IsAssignableFrom(DefaultDictionaryType))
                {
                    _createDictionary = DefaultDictionaryType.CreateDefaultConstructorFunc <object>();
                }
                else
                {
                    var dictionaryInheritorType =
                        _options.ExtraTypes.FirstOrDefault(t =>
                                                           !t.IsInterface &&
                                                           !t.IsAbstract &&
                                                           DictionaryType.IsAssignableFrom(t) &&
                                                           t.HasDefaultConstructor());
                    _createDictionary = dictionaryInheritorType.CreateDefaultConstructorFunc <object>();
                }
            }
            else if (DictionaryType.HasDefaultConstructor())
            {
                _createDictionary = DictionaryType.CreateDefaultConstructorFunc <object>();
            }
            else
            {
                throw new ArgumentException("Unable to find suitable dictionary to create.");
            }
            // ReSharper restore DoNotCallOverridableMethodsInConstructor
        }