示例#1
0
        protected ListSerializer(EncryptAttribute encryptAttribute, IXmlSerializerOptions options, string itemElementName)                                                             // ReSharper disable DoNotCallOverridableMethodsInConstructor
        {
            _encryptAttribute = encryptAttribute ?? (EncryptAttribute)Attribute.GetCustomAttribute(ItemType, typeof(EncryptAttribute));
            _options          = options;
            _itemElementName  = string.IsNullOrEmpty(itemElementName) ? DefaultItemElementName : itemElementName;
            _itemSerializer   = XmlSerializerFactory.Instance.GetSerializer(ItemType, null, _options.WithRootElementName(_itemElementName).AlwaysEmitNil());

            if (CollectionType.IsArray)
            {
                _createCollection = DefaultCollectionType.CreateDefaultConstructorFunc <object>();
            }
            else if (CollectionType.IsReadOnlyCollection())
            {
                _createCollection = DefaultCollectionType.CreateDefaultConstructorFunc <object>();
            }
            else if (CollectionType.IsInterface || CollectionType.IsAbstract)
            {
                if (CollectionType.IsAssignableFrom(DefaultCollectionType))
                {
                    _createCollection = DefaultCollectionType.CreateDefaultConstructorFunc <object>();
                }
                else
                {
                    var collectionInheritorType =
                        _options.ExtraTypes.FirstOrDefault(t =>
                                                           !t.IsInterface &&
                                                           !t.IsAbstract &&
                                                           CollectionType.IsAssignableFrom(t) &&
                                                           t.HasDefaultConstructor());
                    _createCollection = collectionInheritorType.CreateDefaultConstructorFunc <object>();
                }
            }
            else if (CollectionType.HasDefaultConstructor())
            {
                _createCollection = CollectionType.CreateDefaultConstructorFunc <object>();
            }
            else
            {
                throw new ArgumentException("Unable to find suitable collection to create.");
            }
        }                                                                                                                                           // ReSharper restore DoNotCallOverridableMethodsInConstructor