ReflectionUtil.cs 16 KB

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