ReflectionUtil.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Drawing;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Reflection;
  9. using System.Resources;
  10. using System.Text;
  11. namespace Masuit.Tools.Reflection
  12. {
  13. /// <summary>
  14. /// 反射操作辅助类,如获取或设置字段、属性的值等反射信息。
  15. /// </summary>
  16. public static class ReflectionUtil
  17. {
  18. #region 属性字段设置
  19. #pragma warning disable 1591
  20. public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
  21. #pragma warning restore 1591
  22. /// <summary>
  23. /// 执行方法
  24. /// </summary>
  25. /// <param name="obj">反射对象</param>
  26. /// <param name="methodName">方法名,区分大小写</param>
  27. /// <param name="args">方法参数</param>
  28. /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
  29. /// <returns>T类型</returns>
  30. public static T InvokeMethod<T>(this object obj, string methodName, object[] args) where T : class
  31. {
  32. T objReturn;
  33. Type type = obj.GetType();
  34. objReturn = type.InvokeMember(methodName, bf | BindingFlags.InvokeMethod, null, obj, args) as T;
  35. return objReturn;
  36. }
  37. /// <summary>
  38. /// 设置字段
  39. /// </summary>
  40. /// <param name="obj">反射对象</param>
  41. /// <param name="name">字段名</param>
  42. /// <param name="value">值</param>
  43. public static void SetField(this object obj, string name, object value)
  44. {
  45. FieldInfo fi = obj.GetType().GetField(name, bf);
  46. fi.SetValue(obj, value);
  47. }
  48. /// <summary>
  49. /// 获取字段
  50. /// </summary>
  51. /// <param name="obj">反射对象</param>
  52. /// <param name="name">字段名</param>
  53. /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
  54. /// <returns>T类型</returns>
  55. public static T GetField<T>(this object obj, string name) where T : class
  56. {
  57. FieldInfo fi = obj.GetType().GetField(name, bf);
  58. return fi.GetValue(obj) as T;
  59. }
  60. /// <summary>
  61. /// 获取所有的字段信息
  62. /// </summary>
  63. /// <param name="obj">反射对象</param>
  64. /// <returns>字段信息</returns>
  65. public static FieldInfo[] GetFields(this object obj)
  66. {
  67. FieldInfo[] fieldInfos = obj.GetType().GetFields(bf);
  68. return fieldInfos;
  69. }
  70. /// <summary>
  71. /// 设置属性
  72. /// </summary>
  73. /// <param name="obj">反射对象</param>
  74. /// <param name="name">属性名</param>
  75. /// <param name="value">值</param>
  76. public static void SetProperty(this object obj, string name, object value)
  77. {
  78. PropertyInfo fieldInfo = obj.GetType().GetProperty(name, bf);
  79. value = Convert.ChangeType(value, fieldInfo.PropertyType);
  80. fieldInfo.SetValue(obj, value, null);
  81. }
  82. /// <summary>
  83. /// 获取属性
  84. /// </summary>
  85. /// <param name="obj">反射对象</param>
  86. /// <param name="name">属性名</param>
  87. /// <typeparam name="T">约束返回的T必须是引用类型</typeparam>
  88. /// <returns>T类型</returns>
  89. public static T GetProperty<T>(this object obj, string name) where T : class
  90. {
  91. PropertyInfo fieldInfo = obj.GetType().GetProperty(name, bf);
  92. return fieldInfo.GetValue(obj, null) as T;
  93. }
  94. /// <summary>
  95. /// 获取所有的属性信息
  96. /// </summary>
  97. /// <param name="obj">反射对象</param>
  98. /// <returns>属性信息</returns>
  99. public static PropertyInfo[] GetProperties(this object obj)
  100. {
  101. PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bf);
  102. return propertyInfos;
  103. }
  104. #endregion
  105. #region 获取Description
  106. /// <overloads>
  107. /// Get The Member Description using Description Attribute.
  108. /// </overloads>
  109. /// <summary>
  110. /// Get The Enum Field Description using Description Attribute.
  111. /// </summary>
  112. /// <param name="value">The value.</param>
  113. /// <returns>return description or value.ToString()</returns>
  114. public static string GetDescription(this Enum value)
  115. {
  116. return GetDescription(value, null);
  117. }
  118. /// <summary>
  119. /// Get The Enum Field Description using Description Attribute and
  120. /// objects to format the Description.
  121. /// </summary>
  122. /// <param name="value">Enum For Which description is required.</param>
  123. /// <param name="args">An Object array containing zero or more objects to format.</param>
  124. /// <returns>return null if DescriptionAttribute is not found or return type description</returns>
  125. /// <exception cref="ArgumentNullException"><paramref name="value"/>"/> is <c>null</c>.</exception>
  126. public static string GetDescription(this Enum value, params object[] args)
  127. {
  128. if (value == null)
  129. {
  130. throw new ArgumentNullException(nameof(value));
  131. }
  132. FieldInfo fi = value.GetType().GetField(value.ToString());
  133. DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
  134. var text = attributes.Length > 0 ? attributes[0].Description : value.ToString();
  135. if ((args != null) && (args.Length > 0))
  136. {
  137. return string.Format(null, text, args);
  138. }
  139. return text;
  140. }
  141. /// <summary>
  142. /// Get The Type Description using Description Attribute.
  143. /// </summary>
  144. /// <param name="member">Specified Member for which Info is Required</param>
  145. /// <returns>return null if DescriptionAttribute is not found or return type description</returns>
  146. public static string GetDescription(this MemberInfo member)
  147. {
  148. return GetDescription(member, null);
  149. }
  150. /// <summary>
  151. /// Get The Type Description using Description Attribute and
  152. /// objects to format the Description.
  153. /// </summary>
  154. /// <param name="member"> Specified Member for which Info is Required</param>
  155. /// <param name="args">An Object array containing zero or more objects to format.</param>
  156. /// <returns>return <see cref="String.Empty"/> if DescriptionAttribute is
  157. /// not found or return type description</returns>
  158. /// <exception cref="ArgumentNullException"><paramref name="member"/>"/> is <c>null</c>.</exception>
  159. public static string GetDescription(this MemberInfo member, params object[] args)
  160. {
  161. string text1;
  162. if (member == null)
  163. {
  164. throw new ArgumentNullException(nameof(member));
  165. }
  166. if (member.IsDefined(typeof(DescriptionAttribute), false))
  167. {
  168. DescriptionAttribute[] attributes = (DescriptionAttribute[])member.GetCustomAttributes(typeof(DescriptionAttribute), false);
  169. text1 = attributes[0].Description;
  170. }
  171. else
  172. {
  173. return string.Empty;
  174. }
  175. if (args != null && args.Length > 0)
  176. {
  177. return string.Format(null, text1, args);
  178. }
  179. return text1;
  180. }
  181. #endregion
  182. #region 获取Attribute信息
  183. /// <overloads>
  184. /// Gets the specified object attributes
  185. /// </overloads>
  186. /// <summary>
  187. /// Gets the specified object attributes for assembly as specified by type
  188. /// </summary>
  189. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  190. /// <param name="assembly">the assembly in which the specified attribute is defined</param>
  191. /// <returns>Attribute as Object or null if not found.</returns>
  192. /// <exception cref="ArgumentNullException"><paramref name="attributeType"/>"/> is <c>null</c>.</exception>
  193. public static object GetAttribute(this Type attributeType, Assembly assembly)
  194. {
  195. if (attributeType == null)
  196. {
  197. throw new ArgumentNullException(nameof(attributeType));
  198. }
  199. if (assembly == null)
  200. {
  201. throw new ArgumentNullException(nameof(assembly));
  202. }
  203. if (assembly.IsDefined(attributeType, false))
  204. {
  205. object[] attributes = assembly.GetCustomAttributes(attributeType, false);
  206. return attributes[0];
  207. }
  208. return null;
  209. }
  210. /// <summary>
  211. /// Gets the specified object attributes for type as specified by type
  212. /// </summary>
  213. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  214. /// <param name="type">the type on which the specified attribute is defined</param>
  215. /// <returns>Attribute as Object or null if not found.</returns>
  216. public static object GetAttribute(this Type attributeType, MemberInfo type)
  217. {
  218. return GetAttribute(attributeType, type, false);
  219. }
  220. /// <summary>
  221. /// Gets the specified object attributes for type as specified by type with option to serach parent
  222. /// </summary>
  223. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  224. /// <param name="type">the type on which the specified attribute is defined</param>
  225. /// <param name="searchParent">if set to <see langword="true"/> [search parent].</param>
  226. /// <returns>
  227. /// Attribute as Object or null if not found.
  228. /// </returns>
  229. public static object GetAttribute(this Type attributeType, MemberInfo type, bool searchParent)
  230. {
  231. if (type == null)
  232. {
  233. return null;
  234. }
  235. if (!(attributeType.IsSubclassOf(typeof(Attribute))))
  236. {
  237. return null;
  238. }
  239. if (type.IsDefined(attributeType, searchParent))
  240. {
  241. object[] attributes = type.GetCustomAttributes(attributeType, searchParent);
  242. if (attributes.Length > 0)
  243. {
  244. return attributes[0];
  245. }
  246. }
  247. return null;
  248. }
  249. /// <summary>
  250. /// Gets the collection of all specified object attributes for type as specified by type
  251. /// </summary>
  252. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  253. /// <param name="type">the type on which the specified attribute is defined</param>
  254. /// <returns>Attribute as Object or null if not found.</returns>
  255. public static object[] GetAttributes(this Type attributeType, MemberInfo type)
  256. {
  257. return GetAttributes(attributeType, type, false);
  258. }
  259. /// <summary>
  260. /// Gets the collection of all specified object attributes for type as specified by type with option to serach parent
  261. /// </summary>
  262. /// <param name="attributeType">The attribute Type for which the custom attributes are to be returned.</param>
  263. /// <param name="type">the type on which the specified attribute is defined</param>
  264. /// <param name="searchParent">The attribute Type for which the custom attribute is to be returned.</param>
  265. /// <returns>
  266. /// Attribute as Object or null if not found.
  267. /// </returns>
  268. public static object[] GetAttributes(this Type attributeType, MemberInfo type, bool searchParent)
  269. {
  270. if (type == null)
  271. {
  272. return null;
  273. }
  274. if (!(attributeType.IsSubclassOf(typeof(Attribute))))
  275. {
  276. return null;
  277. }
  278. if (type.IsDefined(attributeType, false))
  279. {
  280. return type.GetCustomAttributes(attributeType, searchParent);
  281. }
  282. return null;
  283. }
  284. #endregion
  285. #region 资源获取
  286. /// <summary>
  287. /// 根据资源名称获取图片资源流
  288. /// </summary>
  289. /// <param name="_"></param>
  290. /// <param name="resourceName">资源的名称</param>
  291. /// <returns>数据流</returns>
  292. public static Stream GetImageResource(this Assembly _, string resourceName)
  293. {
  294. Assembly asm = Assembly.GetExecutingAssembly();
  295. return asm.GetManifestResourceStream(resourceName);
  296. }
  297. /// <summary>
  298. /// 获取程序集资源的位图资源
  299. /// </summary>
  300. /// <param name="assemblyType">程序集中的某一对象类型</param>
  301. /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
  302. /// <param name="imageName">资源项名称</param>
  303. public static Bitmap LoadBitmap(this Type assemblyType, string resourceHolder, string imageName)
  304. {
  305. Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
  306. ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
  307. return (Bitmap)rm.GetObject(imageName);
  308. }
  309. /// <summary>
  310. /// 获取程序集资源的文本资源
  311. /// </summary>
  312. /// <param name="assemblyType">程序集中的某一对象类型</param>
  313. /// <param name="resName">资源项名称</param>
  314. /// <param name="resourceHolder">资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。</param>
  315. public static string GetStringRes(this Type assemblyType, string resName, string resourceHolder)
  316. {
  317. Assembly thisAssembly = Assembly.GetAssembly(assemblyType);
  318. ResourceManager rm = new ResourceManager(resourceHolder, thisAssembly);
  319. return rm.GetString(resName);
  320. }
  321. /// <summary>
  322. /// 获取程序集嵌入资源的文本形式
  323. /// </summary>
  324. /// <param name="assemblyType">程序集中的某一对象类型</param>
  325. /// <param name="charset">字符集编码</param>
  326. /// <param name="resName">嵌入资源相对路径</param>
  327. /// <returns>如没找到该资源则返回空字符</returns>
  328. public static string GetManifestString(this Type assemblyType, string charset, string resName)
  329. {
  330. Assembly asm = Assembly.GetAssembly(assemblyType);
  331. Stream st = asm.GetManifestResourceStream(string.Concat(assemblyType.Namespace, ".", resName.Replace("/", ".")));
  332. if (st == null)
  333. {
  334. return "";
  335. }
  336. int iLen = (int)st.Length;
  337. byte[] bytes = new byte[iLen];
  338. st.Read(bytes, 0, iLen);
  339. return (bytes != null) ? Encoding.GetEncoding(charset).GetString(bytes) : "";
  340. }
  341. #endregion
  342. #region 创建实例
  343. /// <summary>
  344. /// 获取默认实例
  345. /// </summary>
  346. /// <param name="type">类型</param>
  347. /// <returns></returns>
  348. public static object GetInstance(this Type type)
  349. {
  350. return GetInstance<TypeToIgnore>(type, null);
  351. }
  352. /// <summary>
  353. /// 获取默认实例
  354. /// </summary>
  355. /// <param name="type">类型</param>
  356. /// <returns></returns>
  357. public static object GetInstance(string type)
  358. {
  359. return GetInstance<TypeToIgnore>(Type.GetType(type), null);
  360. }
  361. /// <summary>
  362. /// 获取一个构造参数的实例
  363. /// </summary>
  364. /// <typeparam name="TArg">参数类型</typeparam>
  365. /// <param name="type">实例类型</param>
  366. /// <param name="argument">参数值</param>
  367. /// <returns></returns>
  368. public static object GetInstance<TArg>(this Type type, TArg argument)
  369. {
  370. return GetInstance<TArg, TypeToIgnore>(type, argument, null);
  371. }
  372. /// <summary>
  373. /// 获取一个构造参数的实例
  374. /// </summary>
  375. /// <typeparam name="TArg">参数类型</typeparam>
  376. /// <param name="type">实例类型</param>
  377. /// <param name="argument">参数值</param>
  378. /// <returns></returns>
  379. public static object GetInstance<TArg>(string type, TArg argument)
  380. {
  381. return GetInstance<TArg, TypeToIgnore>(Type.GetType(type), argument, null);
  382. }
  383. /// <summary>
  384. /// 获取2个构造参数的实例
  385. /// </summary>
  386. /// <typeparam name="TArg1">参数类型</typeparam>
  387. /// <typeparam name="TArg2">参数类型</typeparam>
  388. /// <param name="type">实例类型</param>
  389. /// <param name="argument1">参数值</param>
  390. /// <param name="argument2">参数值</param>
  391. /// <returns></returns>
  392. public static object GetInstance<TArg1, TArg2>(this Type type, TArg1 argument1, TArg2 argument2)
  393. {
  394. return GetInstance<TArg1, TArg2, TypeToIgnore>(type, argument1, argument2, null);
  395. }
  396. /// <summary>
  397. /// 获取2个构造参数的实例
  398. /// </summary>
  399. /// <typeparam name="TArg1">参数类型</typeparam>
  400. /// <typeparam name="TArg2">参数类型</typeparam>
  401. /// <param name="type">实例类型</param>
  402. /// <param name="argument1">参数值</param>
  403. /// <param name="argument2">参数值</param>
  404. /// <returns></returns>
  405. public static object GetInstance<TArg1, TArg2>(string type, TArg1 argument1, TArg2 argument2)
  406. {
  407. return GetInstance<TArg1, TArg2, TypeToIgnore>(Type.GetType(type), argument1, argument2, null);
  408. }
  409. /// <summary>
  410. /// 获取3个构造参数的实例
  411. /// </summary>
  412. /// <typeparam name="TArg1">参数类型</typeparam>
  413. /// <typeparam name="TArg2">参数类型</typeparam>
  414. /// <typeparam name="TArg3">参数类型</typeparam>
  415. /// <param name="type">实例类型</param>
  416. /// <param name="argument1">参数值</param>
  417. /// <param name="argument2">参数值</param>
  418. /// <param name="argument3">参数值</param>
  419. /// <returns></returns>
  420. public static object GetInstance<TArg1, TArg2, TArg3>(this Type type, TArg1 argument1, TArg2 argument2, TArg3 argument3)
  421. {
  422. return InstanceCreationFactory<TArg1, TArg2, TArg3>.CreateInstanceOf(type, argument1, argument2, argument3);
  423. }
  424. /// <summary>
  425. /// 获取3个构造参数的实例
  426. /// </summary>
  427. /// <typeparam name="TArg1">参数类型</typeparam>
  428. /// <typeparam name="TArg2">参数类型</typeparam>
  429. /// <typeparam name="TArg3">参数类型</typeparam>
  430. /// <param name="type">实例类型</param>
  431. /// <param name="argument1">参数值</param>
  432. /// <param name="argument2">参数值</param>
  433. /// <param name="argument3">参数值</param>
  434. /// <returns></returns>
  435. public static object GetInstance<TArg1, TArg2, TArg3>(string type, TArg1 argument1, TArg2 argument2, TArg3 argument3)
  436. {
  437. return InstanceCreationFactory<TArg1, TArg2, TArg3>.CreateInstanceOf(Type.GetType(type), argument1, argument2, argument3);
  438. }
  439. private class TypeToIgnore
  440. {
  441. }
  442. private static class InstanceCreationFactory<TArg1, TArg2, TArg3>
  443. {
  444. private static readonly Dictionary<Type, Func<TArg1, TArg2, TArg3, object>> InstanceCreationMethods = new Dictionary<Type, Func<TArg1, TArg2, TArg3, object>>();
  445. public static object CreateInstanceOf(Type type, TArg1 arg1, TArg2 arg2, TArg3 arg3)
  446. {
  447. CacheInstanceCreationMethodIfRequired(type);
  448. return InstanceCreationMethods[type].Invoke(arg1, arg2, arg3);
  449. }
  450. private static void CacheInstanceCreationMethodIfRequired(Type type)
  451. {
  452. if (InstanceCreationMethods.ContainsKey(type))
  453. {
  454. return;
  455. }
  456. var argumentTypes = new[]
  457. {
  458. typeof(TArg1),
  459. typeof(TArg2),
  460. typeof(TArg3)
  461. };
  462. Type[] constructorArgumentTypes = argumentTypes.Where(t => t != typeof(TypeToIgnore)).ToArray();
  463. var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.HasThis, constructorArgumentTypes, new ParameterModifier[0]);
  464. var lamdaParameterExpressions = new[]
  465. {
  466. Expression.Parameter(typeof(TArg1), "param1"),
  467. Expression.Parameter(typeof(TArg2), "param2"),
  468. Expression.Parameter(typeof(TArg3), "param3")
  469. };
  470. var constructorParameterExpressions = lamdaParameterExpressions.Take(constructorArgumentTypes.Length).ToArray();
  471. var constructorCallExpression = Expression.New(constructor, constructorParameterExpressions);
  472. var constructorCallingLambda = Expression.Lambda<Func<TArg1, TArg2, TArg3, object>>(constructorCallExpression, lamdaParameterExpressions).Compile();
  473. InstanceCreationMethods[type] = constructorCallingLambda;
  474. }
  475. }
  476. #endregion
  477. }
  478. }