PageRenderTime 94ms CodeModel.GetById 91ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/src/LinFu.Reflection/ListLoader.cs

http://github.com/philiplaureano/LinFu
C# | 61 lines | 38 code | 7 blank | 16 comment | 3 complexity | 44335fed7f44551f779f7bfb0a3172e6 MD5 | raw file
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4
 5namespace LinFu.Reflection
 6{
 7    /// <summary>
 8    ///     Represents an action loader that can load collections from types embedded within a given assembly.
 9    /// </summary>
10    /// <typeparam name="T">The collection item type.</typeparam>
11    public class CollectionLoader<T> : IActionLoader<ICollection<T>, Type>
12        where T : class
13    {
14        /// <summary>
15        ///     Creates the list of actions that load the target collection into memory.
16        /// </summary>
17        /// <param name="input">The source type.</param>
18        /// <returns>A list of actions that load the target collection into memory.</returns>
19        public IEnumerable<Action<ICollection<T>>> Load(Type input)
20        {
21            var actionList = new List<Action<ICollection<T>>>();
22
23            var component = (T) Activator.CreateInstance(input);
24            actionList.Add(items => items.Add(component));
25
26            return actionList;
27        }
28
29        /// <summary>
30        ///     Determines whether or not the given type can be loaded into memory.
31        /// </summary>
32        /// <param name="inputType">The source type.</param>
33        /// <returns>Returns <c>true</c> if the type can be loaded into memory; otherwise, it will return <c>false</c>.</returns>
34        public bool CanLoad(Type inputType)
35        {
36            try
37            {
38                if (!typeof(T).IsAssignableFrom(inputType))
39                    return false;
40
41                if (!inputType.IsClass)
42                    return false;
43
44                if (inputType.IsAbstract)
45                    return false;
46            }
47            catch (TypeInitializationException)
48            {
49                // Ignore the error
50                return false;
51            }
52            catch (FileNotFoundException)
53            {
54                // Ignore the error
55                return false;
56            }
57
58            return true;
59        }
60    }
61}