AssemblyUtil.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Reflection;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Globalization;
  8. #if !SILVERLIGHT
  9. using System.Runtime.Serialization.Formatters.Binary;
  10. #endif
  11. namespace SuperSocket.Common
  12. {
  13. /// <summary>
  14. /// Assembly Util Class
  15. /// </summary>
  16. public static class AssemblyUtil
  17. {
  18. /// <summary>
  19. /// Creates the instance from type name.
  20. /// </summary>
  21. /// <typeparam name="T"></typeparam>
  22. /// <param name="type">The type.</param>
  23. /// <returns></returns>
  24. public static T CreateInstance<T>(string type)
  25. {
  26. return CreateInstance<T>(type, new object[0]);
  27. }
  28. /// <summary>
  29. /// Creates the instance from type name and parameters.
  30. /// </summary>
  31. /// <typeparam name="T"></typeparam>
  32. /// <param name="type">The type.</param>
  33. /// <param name="parameters">The parameters.</param>
  34. /// <returns></returns>
  35. public static T CreateInstance<T>(string type, object[] parameters)
  36. {
  37. Type instanceType = null;
  38. var result = default(T);
  39. instanceType = Type.GetType(type, true);
  40. if (instanceType == null)
  41. throw new Exception(string.Format("The type '{0}' was not found!", type));
  42. object instance = Activator.CreateInstance(instanceType, parameters);
  43. result = (T)instance;
  44. return result;
  45. }
  46. /// <summary>
  47. /// Gets the type by the full name, also return matched generic type without checking generic type parameters in the name.
  48. /// </summary>
  49. /// <param name="fullTypeName">Full name of the type.</param>
  50. /// <param name="throwOnError">if set to <c>true</c> [throw on error].</param>
  51. /// <param name="ignoreCase">if set to <c>true</c> [ignore case].</param>
  52. /// <returns></returns>
  53. #if !NET35
  54. public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase)
  55. {
  56. var targetType = Type.GetType(fullTypeName, false, ignoreCase);
  57. if (targetType != null)
  58. return targetType;
  59. var names = fullTypeName.Split(',');
  60. var assemblyName = names[1].Trim();
  61. try
  62. {
  63. var assembly = Assembly.Load(assemblyName);
  64. var typeNamePrefix = names[0].Trim() + "`";
  65. var matchedTypes = assembly.GetExportedTypes().Where(t => t.IsGenericType
  66. && t.FullName.StartsWith(typeNamePrefix, ignoreCase, CultureInfo.InvariantCulture)).ToArray();
  67. if (matchedTypes.Length != 1)
  68. return null;
  69. return matchedTypes[0];
  70. }
  71. catch (Exception e)
  72. {
  73. if (throwOnError)
  74. throw e;
  75. return null;
  76. }
  77. }
  78. #else
  79. public static Type GetType(string fullTypeName, bool throwOnError, bool ignoreCase)
  80. {
  81. return Type.GetType(fullTypeName, null, (a, n, ign) =>
  82. {
  83. var targetType = a.GetType(n, false, ign);
  84. if (targetType != null)
  85. return targetType;
  86. var typeNamePrefix = n + "`";
  87. var matchedTypes = a.GetExportedTypes().Where(t => t.IsGenericType
  88. && t.FullName.StartsWith(typeNamePrefix, ign, CultureInfo.InvariantCulture)).ToArray();
  89. if (matchedTypes.Length != 1)
  90. return null;
  91. return matchedTypes[0];
  92. }, throwOnError, ignoreCase);
  93. }
  94. #endif
  95. /// <summary>
  96. /// Gets the implement types from assembly.
  97. /// </summary>
  98. /// <typeparam name="TBaseType">The type of the base type.</typeparam>
  99. /// <param name="assembly">The assembly.</param>
  100. /// <returns></returns>
  101. public static IEnumerable<Type> GetImplementTypes<TBaseType>(this Assembly assembly)
  102. {
  103. return assembly.GetExportedTypes().Where(t =>
  104. t.IsSubclassOf(typeof(TBaseType)) && t.IsClass && !t.IsAbstract);
  105. }
  106. /// <summary>
  107. /// Gets the implemented objects by interface.
  108. /// </summary>
  109. /// <typeparam name="TBaseInterface">The type of the base interface.</typeparam>
  110. /// <param name="assembly">The assembly.</param>
  111. /// <returns></returns>
  112. public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly)
  113. where TBaseInterface : class
  114. {
  115. return GetImplementedObjectsByInterface<TBaseInterface>(assembly, typeof(TBaseInterface));
  116. }
  117. /// <summary>
  118. /// Gets the implemented objects by interface.
  119. /// </summary>
  120. /// <typeparam name="TBaseInterface">The type of the base interface.</typeparam>
  121. /// <param name="assembly">The assembly.</param>
  122. /// <param name="targetType">Type of the target.</param>
  123. /// <returns></returns>
  124. public static IEnumerable<TBaseInterface> GetImplementedObjectsByInterface<TBaseInterface>(this Assembly assembly, Type targetType)
  125. where TBaseInterface : class
  126. {
  127. Type[] arrType = assembly.GetExportedTypes();
  128. var result = new List<TBaseInterface>();
  129. for (int i = 0; i < arrType.Length; i++)
  130. {
  131. var currentImplementType = arrType[i];
  132. if (currentImplementType.IsAbstract)
  133. continue;
  134. if (!targetType.IsAssignableFrom(currentImplementType))
  135. continue;
  136. result.Add((TBaseInterface)Activator.CreateInstance(currentImplementType));
  137. }
  138. return result;
  139. }
  140. #if SILVERLIGHT
  141. #else
  142. /// <summary>
  143. /// Clone object in binary format.
  144. /// </summary>
  145. /// <typeparam name="T"></typeparam>
  146. /// <param name="target">The target.</param>
  147. /// <returns></returns>
  148. public static T BinaryClone<T>(this T target)
  149. {
  150. BinaryFormatter formatter = new BinaryFormatter();
  151. using (MemoryStream ms = new MemoryStream())
  152. {
  153. formatter.Serialize(ms, target);
  154. ms.Position = 0;
  155. return (T)formatter.Deserialize(ms);
  156. }
  157. }
  158. #endif
  159. /// <summary>
  160. /// Copies the properties of one object to another object.
  161. /// </summary>
  162. /// <typeparam name="T"></typeparam>
  163. /// <param name="source">The source.</param>
  164. /// <param name="target">The target.</param>
  165. /// <returns></returns>
  166. public static T CopyPropertiesTo<T>(this T source, T target)
  167. {
  168. return source.CopyPropertiesTo(p => true, target);
  169. }
  170. /// <summary>
  171. /// Copies the properties of one object to another object.
  172. /// </summary>
  173. /// <typeparam name="T"></typeparam>
  174. /// <param name="source">The source.</param>
  175. /// <param name="predict">The properties predict.</param>
  176. /// <param name="target">The target.</param>
  177. /// <returns></returns>
  178. public static T CopyPropertiesTo<T>(this T source, Predicate<PropertyInfo> predict, T target)
  179. {
  180. PropertyInfo[] properties = source.GetType()
  181. .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
  182. Dictionary<string, PropertyInfo> sourcePropertiesDict = properties.ToDictionary(p => p.Name);
  183. PropertyInfo[] targetProperties = target.GetType()
  184. .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty)
  185. .Where(p => predict(p)).ToArray();
  186. for (int i = 0; i < targetProperties.Length; i++)
  187. {
  188. var p = targetProperties[i];
  189. PropertyInfo sourceProperty;
  190. if (sourcePropertiesDict.TryGetValue(p.Name, out sourceProperty))
  191. {
  192. if (sourceProperty.PropertyType != p.PropertyType)
  193. continue;
  194. if (!sourceProperty.PropertyType.IsSerializable)
  195. continue;
  196. p.SetValue(target, sourceProperty.GetValue(source, null), null);
  197. }
  198. }
  199. return target;
  200. }
  201. /// <summary>
  202. /// Gets the assemblies from string.
  203. /// </summary>
  204. /// <param name="assemblyDef">The assembly def.</param>
  205. /// <returns></returns>
  206. public static IEnumerable<Assembly> GetAssembliesFromString(string assemblyDef)
  207. {
  208. return GetAssembliesFromStrings(assemblyDef.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries));
  209. }
  210. /// <summary>
  211. /// Gets the assemblies from strings.
  212. /// </summary>
  213. /// <param name="assemblies">The assemblies.</param>
  214. /// <returns></returns>
  215. public static IEnumerable<Assembly> GetAssembliesFromStrings(string[] assemblies)
  216. {
  217. List<Assembly> result = new List<Assembly>(assemblies.Length);
  218. foreach (var a in assemblies)
  219. {
  220. result.Add(Assembly.Load(a));
  221. }
  222. return result;
  223. }
  224. }
  225. }