GenericListConverter
using Castle.Core.Configuration;
using Castle.Core.Internal;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Util;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
namespace Castle.MicroKernel.SubSystems.Conversion
{
[Serializable]
public class GenericListConverter : AbstractTypeConverter
{
private class ListHelper<T> : IGenericCollectionConverterHelper
{
private readonly GenericListConverter parent;
public ListHelper(GenericListConverter parent)
{
this.parent = parent;
}
public object ConvertConfigurationToCollection(IConfiguration configuration)
{
List<T> list = new List<T>();
foreach (IConfiguration item2 in (List<IConfiguration>)configuration.get_Children()) {
T item = parent.Context.Composition.PerformConversion<T>(item2);
list.Add(item);
}
return list;
}
}
public override bool CanHandleType(Type type)
{
if (!type.GetTypeInfo().IsGenericType)
return false;
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (!(genericTypeDefinition == typeof(IList<>)) && !(genericTypeDefinition == typeof(ICollection<>)) && !(genericTypeDefinition == typeof(List<>)))
return genericTypeDefinition == typeof(IEnumerable<>);
return true;
}
public override object PerformConversion(string value, Type targetType)
{
if (ReferenceExpressionUtil.IsReference(value)) {
string text = ReferenceExpressionUtil.ExtractComponentName(value);
IHandler handler = base.Context.Kernel.LoadHandlerByName(text, targetType, null);
if (handler == null)
throw new ConverterException($"""{text}""");
return handler.Resolve(base.Context.CurrentCreationContext ?? CreationContext.CreateEmpty());
}
throw new NotImplementedException();
}
public override object PerformConversion(IConfiguration configuration, Type targetType)
{
Type[] genericArguments = targetType.GetGenericArguments();
if (genericArguments.Length != 1)
throw new ConverterException("Expected type with one generic argument.");
string text = ((NameValueCollection)configuration.get_Attributes())["type"];
Type type = genericArguments[0];
if (text != null)
type = base.Context.Composition.PerformConversion<Type>(text);
return typeof(ListHelper<>).MakeGenericType(type).CreateInstance<IGenericCollectionConverterHelper>(new object[1] {
this
}).ConvertConfigurationToCollection(configuration);
}
}
}