ReflectionUtil.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. using System;
  2. using System.ComponentModel;
  3. using System.Drawing;
  4. using System.IO;
  5. using System.Reflection;
  6. using System.Resources;
  7. using System.Text;
  8. namespace Masuit.Tools.Reflection
  9. {
  10. /// <summary>
  11. /// 反射操作辅助类,如获取或设置字段、属性的值等反射信息。
  12. /// </summary>
  13. public static class ReflectionUtil
  14. {
  15. #region 属性字段设置
  16. #pragma warning disable 1591
  17. public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
  18. #pragma warning restore 1591
  19. /// <summary>
  20. /// 执行方法
  21. /// </summary>
  22. /// <param name="obj">反射对象</param>
  23. /// <param name="methodName">方法名,区分大小写</param>
  24. /// <param name="args">方法参数</param>
  25. /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
  26. /// <returns>T类型</returns>
  27. public static T InvokeMethod<T>(this object obj, string methodName, object[] args) where T : class
  28. {
  29. T objReturn;
  30. Type type = obj.GetType();
  31. objReturn = type.InvokeMember(methodName, bf | BindingFlags.InvokeMethod, null, obj, args) as T;
  32. return objReturn;
  33. }
  34. /// <summary>
  35. /// 设置字段
  36. /// </summary>
  37. /// <param name="obj">反射对象</param>
  38. /// <param name="name">字段名</param>
  39. /// <param name="value">值</param>
  40. public static void SetField(this object obj, string name, object value)
  41. {
  42. FieldInfo fi = obj.GetType().GetField(name, bf);
  43. fi.SetValue(obj, value);
  44. }
  45. /// <summary>
  46. /// 获取字段
  47. /// </summary>
  48. /// <param name="obj">反射对象</param>
  49. /// <param name="name">字段名</param>
  50. /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
  51. /// <returns>T类型</returns>
  52. public static T GetField<T>(this object obj, string name) where T : class
  53. {
  54. FieldInfo fi = obj.GetType().GetField(name, bf);
  55. return fi.GetValue(obj) as T;
  56. }
  57. /// <summary>
  58. /// 获取所有的字段信息
  59. /// </summary>
  60. /// <param name="obj">反射对象</param>
  61. /// <returns>字段信息</returns>
  62. public static FieldInfo[] GetFields(this object obj)
  63. {
  64. FieldInfo[] fieldInfos = obj.GetType().GetFields(bf);
  65. return fieldInfos;
  66. }
  67. /// <summary>
  68. /// 设置属性
  69. /// </summary>
  70. /// <param name="obj">反射对象</param>
  71. /// <param name="name">属性名</param>
  72. /// <param name="value">值</param>
  73. public static void SetProperty(this object obj, string name, object value)
  74. {
  75. PropertyInfo fieldInfo = obj.GetType().GetProperty(name, bf);
  76. value = Convert.ChangeType(value, fieldInfo.PropertyType);
  77. fieldInfo.SetValue(obj, value, null);
  78. }
  79. /// <summary>
  80. /// 获取属性
  81. /// </summary>
  82. /// <param name="obj">反射对象</param>
  83. /// <param name="name">属性名</param>
  84. /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
  85. /// <returns>T类型</returns>
  86. public static T GetProperty<T>(this object obj, string name) where T : class
  87. {
  88. PropertyInfo fieldInfo = obj.GetType().GetProperty(name, bf);
  89. return fieldInfo.GetValue(obj, null) as T;
  90. }
  91. /// <summary>
  92. /// 获取所有的属性信息
  93. /// </summary>
  94. /// <param name="obj">反射对象</param>
  95. /// <returns>属性信息</returns>
  96. public static PropertyInfo[] GetProperties(this object obj)
  97. {
  98. PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bf);
  99. return propertyInfos;
  100. }
  101. #endregion
  102. #region 获取Description
  103. /// <overloads>
  104. /// Get The Member Description using Description Attribute.
  105. /// </overloads>
  106. /// <summary>
  107. /// Get The Enum Field Description using Description Attribute.
  108. /// </summary>
  109. /// <param name="value">The value.</param>
  110. /// <returns>return description or value.ToString()</returns>
  111. public static string GetDescription(this Enum value)
  112. {
  113. return GetDescription(value, null);
  114. }
  115. /// <summary>
  116. /// Get The Enum Field Description using Description Attribute and
  117. /// objects to format the Description.
  118. /// </summary>
  119. /// <param name="value">Enum For Which description is required.</param>
  120. /// <param name="args">An Object array containing zero or more objects to format.</param>
  121. /// <returns>return null if DescriptionAttribute is not found or return type description</returns>
  122. /// <exception cref="ArgumentNullException"><paramref name="value"/>"/> is <c>null</c>.</exception>
  123. public static string GetDescription(this Enum value, params object[] args)
  124. {
  125. if (value == null)
  126. {
  127. throw new ArgumentNullException(nameof(value));
  128. }
  129. FieldInfo fi = value.GetType().GetField(value.ToString());
  130. DescriptionAttribute[] attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
  131. var text1 = (attributes.Length > 0) ? attributes[0].Description : value.ToString();
  132. if ((args != null) && (args.Length > 0))
  133. {
  134. return string.Format(null, text1, args);
  135. }
  136. return text1;
  137. }
  138. /// <summary>
  139. /// Get The Type Description using Description Attribute.
  140. /// </summary>
  141. /// <param name="member">Specified Member for which Info is Required</param>
  142. /// <returns>return null if DescriptionAttribute is not found or return type description</returns>
  143. public static string GetDescription(this MemberInfo member)
  144. {
  145. return GetDescription(member, null);
  146. }
  147. /// <summary>
  148. /// Get The Type Description using Description Attribute and
  149. /// objects to format the Description.
  150. /// </summary>
  151. /// <param name="member"> Specified Member for which Info is Required</param>
  152. /// <param name="args">An Object array containing zero or more objects to format.</param>
  153. /// <returns>return <see cref="String.Empty"/> if DescriptionAttribute is
  154. /// not found or return type description</returns>
  155. /// <exception cref="ArgumentNullException"><paramref name="member"/>"/> is <c>null</c>.</exception>
  156. public static string GetDescription(this MemberInfo member, params object[] args)
  157. {
  158. string text1;
  159. if (member == null)
  160. {
  161. throw new ArgumentNullException(nameof(member));
  162. }
  163. if (member.IsDefined(typeof(DescriptionAttribute), false))
  164. {
  165. DescriptionAttribute[] attributes = (DescriptionAttribute[]) member.GetCustomAttributes(typeof(DescriptionAttribute), false);
  166. text1 = attributes[0].Description;
  167. }
  168. else
  169. {
  170. return string.Empty;
  171. }
  172. if ((args != null) && (args.Length > 0))
  173. {
  174. return string.Format(null, text1, args);
  175. }
  176. return text1;
  177. }
  178. #endregion
  179. #region 获取Attribute信息
  180. /// <overloads>
  181. /// Gets the specified object attributes
  182. /// </overloads>
  183. /// <summary>
  184. /// Gets the specified object attributes for assembly as specified by type
  185. /// </summary>
  186. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  187. /// <param name="assembly">the assembly in which the specified attribute is defined</param>
  188. /// <returns>Attribute as Object or null if not found.</returns>
  189. /// <exception cref="ArgumentNullException"><paramref name="attributeType"/>"/> is <c>null</c>.</exception>
  190. public static object GetAttribute(this Type attributeType, Assembly assembly)
  191. {
  192. if (attributeType == null)
  193. {
  194. throw new ArgumentNullException(nameof(attributeType));
  195. }
  196. if (assembly == null)
  197. {
  198. throw new ArgumentNullException(nameof(assembly));
  199. }
  200. if (assembly.IsDefined(attributeType, false))
  201. {
  202. object[] attributes = assembly.GetCustomAttributes(attributeType, false);
  203. return attributes[0];
  204. }
  205. return null;
  206. }
  207. /// <summary>
  208. /// Gets the specified object attributes for type as specified by type
  209. /// </summary>
  210. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  211. /// <param name="type">the type on which the specified attribute is defined</param>
  212. /// <returns>Attribute as Object or null if not found.</returns>
  213. public static object GetAttribute(this Type attributeType, MemberInfo type)
  214. {
  215. return GetAttribute(attributeType, type, false);
  216. }
  217. /// <summary>
  218. /// Gets the specified object attributes for type as specified by type with option to serach parent
  219. /// </summary>
  220. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  221. /// <param name="type">the type on which the specified attribute is defined</param>
  222. /// <param name="searchParent">if set to <see langword="true"/> [search parent].</param>
  223. /// <returns>
  224. /// Attribute as Object or null if not found.
  225. /// </returns>
  226. public static object GetAttribute(this Type attributeType, MemberInfo type, bool searchParent)
  227. {
  228. if (type == null)
  229. {
  230. return null;
  231. }
  232. if (!(attributeType.IsSubclassOf(typeof(Attribute))))
  233. {
  234. return null;
  235. }
  236. if (type.IsDefined(attributeType, searchParent))
  237. {
  238. object[] attributes = type.GetCustomAttributes(attributeType, searchParent);
  239. if (attributes.Length > 0)
  240. {
  241. return attributes[0];
  242. }
  243. }
  244. return null;
  245. }
  246. /// <summary>
  247. /// Gets the collection of all specified object attributes for type as specified by type
  248. /// </summary>
  249. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  250. /// <param name="type">the type on which the specified attribute is defined</param>
  251. /// <returns>Attribute as Object or null if not found.</returns>
  252. public static object[] GetAttributes(this Type attributeType, MemberInfo type)
  253. {
  254. return GetAttributes(attributeType, type, false);
  255. }
  256. /// <summary>
  257. /// Gets the collection of all specified object attributes for type as specified by type with option to serach parent
  258. /// </summary>
  259. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  260. /// <param name="type">the type on which the specified attribute is defined</param>
  261. /// <param name="searchParent">The attribute Type for which the custom attribute is to be returned.</param>
  262. /// <returns>
  263. /// Attribute as Object or null if not found.
  264. /// </returns>
  265. public static object[] GetAttributes(this Type attributeType, MemberInfo type, bool searchParent)
  266. {
  267. if (type == null)
  268. {
  269. return null;
  270. }
  271. if (!(attributeType.IsSubclassOf(typeof(Attribute))))
  272. {
  273. return null;
  274. }
  275. if (type.IsDefined(attributeType, false))
  276. {
  277. return type.GetCustomAttributes(attributeType, searchParent);
  278. }
  279. return null;
  280. }
  281. #endregion
  282. #region 资源获取
  283. /// <summary>
  284. /// 根据资源名称获取图片资源流
  285. /// </summary>
  286. /// <param name="_"></param>
  287. /// <param name="resourceName">资源的名称</param>
  288. /// <returns>数据流</returns>
  289. public static Stream GetImageResource(this Assembly _, string resourceName)
  290. {
  291. Assembly asm = Assembly.GetExecutingAssembly();
  292. return asm.GetManifestResourceStream(resourceName);
  293. }
  294. /// <summary>
  295. /// 获取程序集资源的位图资源
  296. /// </summary>
  297. /// <param name="assemblyType">程序集中的某一对象类型</param>
  298. /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
  299. /// <param name="imageName">资源项名称</param>
  300. public static Bitmap LoadBitmap(this Type assemblyType, string resourceHolder, string imageName)
  301. {
  302. Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
  303. ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
  304. return (Bitmap) rm.GetObject(imageName);
  305. }
  306. /// <summary>
  307. /// 获取程序集资源的文本资源
  308. /// </summary>
  309. /// <param name="assemblyType">程序集中的某一对象类型</param>
  310. /// <param name="resName">资源项名称</param>
  311. /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
  312. public static string GetStringRes(this Type assemblyType, string resName, string resourceHolder)
  313. {
  314. Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
  315. ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
  316. return rm.GetString(resName);
  317. }
  318. /// <summary>
  319. /// 获取程序集嵌入资源的文本形式
  320. /// </summary>
  321. /// <param name="assemblyType">程序集中的某一对象类型</param>
  322. /// <param name="charset">字符集编码</param>
  323. /// <param name="resName">嵌入资源相对路径</param>
  324. /// <returns>如没找到该资源则返回空字符</returns>
  325. public static string GetManifestString(this Type assemblyType, string charset, string resName)
  326. {
  327. Assembly asm = Assembly.GetAssembly(assemblyType);
  328. Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace, ".", resName.Replace("/", ".")));
  329. if (st == null)
  330. {
  331. return "";
  332. }
  333. int iLen = (int) st.Length;
  334. byte[] bytes = new byte[iLen];
  335. st.Read(bytes, 0, iLen);
  336. return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
  337. }
  338. #endregion
  339. #region 创建对应实例
  340. /// <summary>
  341. /// 创建对应实例
  342. /// </summary>
  343. /// <param name="type">类型</param>
  344. /// <returns>对应实例</returns>
  345. public static T CreateInstance<T>(string type) where T : class
  346. {
  347. Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
  348. foreach (Assembly t in assemblies)
  349. {
  350. var tmp = t.GetType(type);
  351. if (tmp != null)
  352. {
  353. return t.CreateInstance(type) as T;
  354. }
  355. }
  356. return null;
  357. //return Assembly.GetExecutingAssembly().CreateInstance(type);
  358. }
  359. /// <summary>
  360. /// 创建对应实例
  361. /// </summary>
  362. /// <param name="type">类型</param>
  363. /// <returns>对应实例</returns>
  364. public static T CreateInstance<T>(this Type type) where T : class
  365. {
  366. return CreateInstance<T>(type.FullName);
  367. }
  368. #endregion
  369. }
  370. }