forked from nkast/MonoGame
-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
LoadedTypeCollection.cs
74 lines (61 loc) · 2.29 KB
/
LoadedTypeCollection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Microsoft.Xna.Framework.Content.Pipeline
{
/// <summary>
/// A helper for collecting instances of a particular type
/// by scanning the types in loaded assemblies.
/// </summary>
public class LoadedTypeCollection<T> : IEnumerable<T>
{
private static List<T> _all;
public LoadedTypeCollection()
{
// Scan the already loaded assemblies.
if (_all == null)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var asm in assemblies)
ScanAssembly(asm);
}
// Hook into assembly loading events to gather any new
// enumeration types that are found.
AppDomain.CurrentDomain.AssemblyLoad += (sender, args) => ScanAssembly(args.LoadedAssembly);
}
private static void ScanAssembly(Assembly asm)
{
// Initialize the list on first use.
if (_all == null)
_all = new List<T>(24);
var thisAss = typeof(T).Assembly;
// If the assembly doesn't reference our assembly then it
// cannot contain this type... so skip scanning it.
var refAss = asm.GetReferencedAssemblies();
if (thisAss.FullName != asm.FullName && refAss.All(r => r.FullName != thisAss.FullName))
return;
var definedTypes = asm.GetTypes();
foreach (var type in definedTypes)
{
if (!type.IsSubclassOf(typeof(T)) || type.IsAbstract)
continue;
// Create an instance of the type and add it to our list.
var ttype = (T)Activator.CreateInstance(type);
_all.Add(ttype);
}
}
public IEnumerator<T> GetEnumerator()
{
return _all.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}