Skip to content

Instantly share code, notes, and snippets.

@pisceanfoot
Created May 14, 2014 01:18
Show Gist options
  • Save pisceanfoot/b73362d8fd9f81571990 to your computer and use it in GitHub Desktop.
Save pisceanfoot/b73362d8fd9f81571990 to your computer and use it in GitHub Desktop.
ClassLoader reflect
public static class ClassLoader
{
public static List<T> Load<T>(string fileFullPath)
{
return Load<T>(new string[] { fileFullPath });
}
public static List<T> Load<T>(string path, string parttern)
{
string[] files = Directory.GetFiles(path, parttern);
return Load<T>(files);
}
private static List<T> Load<T>(string[] assemblyPathArray)
{
Type type = typeof(T);
if (!type.IsInterface)
{
throw new ArgumentException(string.Format("type T {0} must be a interface", type.FullName));
}
List<T> list = new List<T>();
foreach (string path in assemblyPathArray)
{
try
{
List<T> tmp = LoadAssambly<T>(path);
if (tmp != null && tmp.Count > 0)
{
list.AddRange(tmp);
}
}
catch (Exception ex)
{
Log.Error(new Exception(string.Format("load assembly {0} error", path), ex));
}
}
return list;
}
private static List<T> LoadAssambly<T>(string assemblyPath)
{
List<T> list = new List<T>();
string fullName = typeof(T).FullName;
Assembly assembly = Assembly.LoadFile(assemblyPath);
Type[] typeArray = assembly.GetTypes();
foreach (Type type in typeArray)
{
if (!type.IsPublic)
{
continue;
}
Type find = type.GetInterface(fullName);
if (find != null && find.IsPublic && !type.IsAbstract)
{
T obj = (T)Activator.CreateInstance(type);
list.Add(obj);
}
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment