1 // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle
.MicroKernel
.SubSystems
.Conversion
18 using System
.Collections
.Generic
;
19 using System
.Diagnostics
;
20 using Castle
.Core
.Configuration
;
23 public class GenericListConverter
: AbstractTypeConverter
26 /// Initializes a new instance of the <see cref="GenericListConverter"/> class.
28 public GenericListConverter()
32 public override bool CanHandleType(Type type
)
34 if (!type
.IsGenericType
) return false;
36 Type genericDef
= type
.GetGenericTypeDefinition();
38 return (genericDef
== typeof(IList
<>)
39 || genericDef
== typeof(ICollection
<>)
40 || genericDef
== typeof(List
<>)
41 || genericDef
== typeof(IEnumerable
<>));
44 public override object PerformConversion(String
value, Type targetType
)
46 throw new NotImplementedException();
49 public override object PerformConversion(IConfiguration configuration
, Type targetType
)
51 Debug
.Assert(CanHandleType(targetType
));
53 Type
[] argTypes
= targetType
.GetGenericArguments();
55 if (argTypes
.Length
!= 1)
57 throw new ConverterException("Expected type with one generic argument.");
60 String itemType
= configuration
.Attributes
["type"];
61 Type convertTo
= argTypes
[0];
65 convertTo
= (Type
) Context
.Composition
.PerformConversion(itemType
, typeof(Type
));
68 IGenericCollectionConverterHelper converterHelper
= (IGenericCollectionConverterHelper
)
69 Activator
.CreateInstance(
70 typeof(ListHelper
<>).MakeGenericType(convertTo
),
72 return converterHelper
.ConvertConfigurationToCollection(configuration
);
75 private class ListHelper
<T
> : IGenericCollectionConverterHelper
77 private GenericListConverter parent
;
79 public ListHelper(GenericListConverter parent
)
84 public object ConvertConfigurationToCollection(IConfiguration configuration
)
86 List
<T
> list
= new List
<T
>();
88 foreach(IConfiguration itemConfig
in configuration
.Children
)
90 T item
= (T
) parent
.Context
.Composition
.PerformConversion(itemConfig
, typeof(T
));