/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

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