Reflection.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection.Emit;
  4. using System.Reflection;
  5. using System.Collections;
  6. using System.Text;
  7. #if !SILVERLIGHT
  8. using System.Data;
  9. #endif
  10. using System.Collections.Specialized;
  11. namespace fastJSON
  12. {
  13. internal struct Getters
  14. {
  15. public string Name;
  16. public string lcName;
  17. public Reflection.GenericGetter Getter;
  18. }
  19. internal enum myPropInfoType
  20. {
  21. Int,
  22. Long,
  23. String,
  24. Bool,
  25. DateTime,
  26. Enum,
  27. Guid,
  28. Array,
  29. ByteArray,
  30. Dictionary,
  31. StringKeyDictionary,
  32. NameValue,
  33. StringDictionary,
  34. #if !SILVERLIGHT
  35. Hashtable,
  36. DataSet,
  37. DataTable,
  38. #endif
  39. Custom,
  40. Unknown,
  41. }
  42. internal struct myPropInfo
  43. {
  44. public Type pt;
  45. public Type bt;
  46. public Type changeType;
  47. public Reflection.GenericSetter setter;
  48. public Reflection.GenericGetter getter;
  49. public Type[] GenericTypes;
  50. public string Name;
  51. public myPropInfoType Type;
  52. public bool CanWrite;
  53. public bool IsClass;
  54. public bool IsValueType;
  55. public bool IsGenericType;
  56. public bool IsStruct;
  57. public bool IsInterface;
  58. }
  59. internal sealed class Reflection
  60. {
  61. // Sinlgeton pattern 4 from : http://csharpindepth.com/articles/general/singleton.aspx
  62. private static readonly Reflection instance = new Reflection();
  63. // Explicit static constructor to tell C# compiler
  64. // not to mark type as beforefieldinit
  65. static Reflection()
  66. {
  67. }
  68. private Reflection()
  69. {
  70. }
  71. public static Reflection Instance { get { return instance; } }
  72. internal delegate object GenericSetter(object target, object value);
  73. internal delegate object GenericGetter(object obj);
  74. private delegate object CreateObject();
  75. private SafeDictionary<Type, string> _tyname = new SafeDictionary<Type, string>();
  76. private SafeDictionary<string, Type> _typecache = new SafeDictionary<string, Type>();
  77. private SafeDictionary<Type, CreateObject> _constrcache = new SafeDictionary<Type, CreateObject>();
  78. private SafeDictionary<Type, Getters[]> _getterscache = new SafeDictionary<Type, Getters[]>();
  79. private SafeDictionary<string, Dictionary<string, myPropInfo>> _propertycache = new SafeDictionary<string, Dictionary<string, myPropInfo>>();
  80. private SafeDictionary<Type, Type[]> _genericTypes = new SafeDictionary<Type, Type[]>();
  81. private SafeDictionary<Type, Type> _genericTypeDef = new SafeDictionary<Type, Type>();
  82. #region bjson custom types
  83. internal UnicodeEncoding unicode = new UnicodeEncoding();
  84. internal UTF8Encoding utf8 = new UTF8Encoding();
  85. #endregion
  86. #region json custom types
  87. // JSON custom
  88. internal SafeDictionary<Type, Serialize> _customSerializer = new SafeDictionary<Type, Serialize>();
  89. internal SafeDictionary<Type, Deserialize> _customDeserializer = new SafeDictionary<Type, Deserialize>();
  90. internal object CreateCustom(string v, Type type)
  91. {
  92. Deserialize d;
  93. _customDeserializer.TryGetValue(type, out d);
  94. return d(v);
  95. }
  96. internal void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer)
  97. {
  98. if (type != null && serializer != null && deserializer != null)
  99. {
  100. _customSerializer.Add(type, serializer);
  101. _customDeserializer.Add(type, deserializer);
  102. // reset property cache
  103. Instance.ResetPropertyCache();
  104. }
  105. }
  106. internal bool IsTypeRegistered(Type t)
  107. {
  108. if (_customSerializer.Count == 0)
  109. return false;
  110. Serialize s;
  111. return _customSerializer.TryGetValue(t, out s);
  112. }
  113. #endregion
  114. public Type GetGenericTypeDefinition(Type t)
  115. {
  116. Type tt = null;
  117. if (_genericTypeDef.TryGetValue(t, out tt))
  118. return tt;
  119. else
  120. {
  121. tt = t.GetGenericTypeDefinition();
  122. _genericTypeDef.Add(t, tt);
  123. return tt;
  124. }
  125. }
  126. public Type[] GetGenericArguments(Type t)
  127. {
  128. Type[] tt = null;
  129. if (_genericTypes.TryGetValue(t, out tt))
  130. return tt;
  131. else
  132. {
  133. tt = t.GetGenericArguments();
  134. _genericTypes.Add(t, tt);
  135. return tt;
  136. }
  137. }
  138. public Dictionary<string, myPropInfo> Getproperties(Type type, string typename)
  139. {
  140. Dictionary<string, myPropInfo> sd = null;
  141. if (_propertycache.TryGetValue(typename, out sd))
  142. {
  143. return sd;
  144. }
  145. else
  146. {
  147. sd = new Dictionary<string, myPropInfo>();
  148. var bf = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
  149. PropertyInfo[] pr = type.GetProperties(bf);
  150. foreach (PropertyInfo p in pr)
  151. {
  152. if (p.GetIndexParameters().Length > 0)// Property is an indexer
  153. continue;
  154. myPropInfo d = CreateMyProp(p.PropertyType, p.Name);
  155. d.setter = Reflection.CreateSetMethod(type, p);
  156. if (d.setter != null)
  157. d.CanWrite = true;
  158. d.getter = Reflection.CreateGetMethod(type, p);
  159. sd.Add(p.Name.ToLower(), d);
  160. }
  161. FieldInfo[] fi = type.GetFields(bf);
  162. foreach (FieldInfo f in fi)
  163. {
  164. myPropInfo d = CreateMyProp(f.FieldType, f.Name);
  165. if (f.IsLiteral == false)
  166. {
  167. d.setter = Reflection.CreateSetField(type, f);
  168. if (d.setter != null)
  169. d.CanWrite = true;
  170. d.getter = Reflection.CreateGetField(type, f);
  171. sd.Add(f.Name.ToLower(), d);
  172. }
  173. }
  174. _propertycache.Add(typename, sd);
  175. return sd;
  176. }
  177. }
  178. private myPropInfo CreateMyProp(Type t, string name)
  179. {
  180. myPropInfo d = new myPropInfo();
  181. myPropInfoType d_type = myPropInfoType.Unknown;
  182. if (t == typeof(int) || t == typeof(int?)) d_type = myPropInfoType.Int;
  183. else if (t == typeof(long) || t == typeof(long?)) d_type = myPropInfoType.Long;
  184. else if (t == typeof(string)) d_type = myPropInfoType.String;
  185. else if (t == typeof(bool) || t == typeof(bool?)) d_type = myPropInfoType.Bool;
  186. else if (t == typeof(DateTime) || t == typeof(DateTime?)) d_type = myPropInfoType.DateTime;
  187. else if (t.IsEnum) d_type = myPropInfoType.Enum;
  188. else if (t == typeof(Guid) || t == typeof(Guid?)) d_type = myPropInfoType.Guid;
  189. else if (t == typeof(StringDictionary)) d_type = myPropInfoType.StringDictionary;
  190. else if (t == typeof(NameValueCollection)) d_type = myPropInfoType.NameValue;
  191. else if (t.IsArray)
  192. {
  193. d.bt = t.GetElementType();
  194. if (t == typeof(byte[]))
  195. d_type = myPropInfoType.ByteArray;
  196. else
  197. d_type = myPropInfoType.Array;
  198. }
  199. else if (t.Name.Contains("Dictionary"))
  200. {
  201. d.GenericTypes = Reflection.Instance.GetGenericArguments(t);
  202. if (d.GenericTypes.Length > 0 && d.GenericTypes[0] == typeof(string))
  203. d_type = myPropInfoType.StringKeyDictionary;
  204. else
  205. d_type = myPropInfoType.Dictionary;
  206. }
  207. #if !SILVERLIGHT
  208. else if (t == typeof(Hashtable)) d_type = myPropInfoType.Hashtable;
  209. else if (t == typeof(DataSet)) d_type = myPropInfoType.DataSet;
  210. else if (t == typeof(DataTable)) d_type = myPropInfoType.DataTable;
  211. #endif
  212. else if (IsTypeRegistered(t))
  213. d_type = myPropInfoType.Custom;
  214. if (t.IsValueType && !t.IsPrimitive && !t.IsEnum && t != typeof(decimal))
  215. d.IsStruct = true;
  216. d.IsInterface = t.IsInterface;
  217. d.IsClass = t.IsClass;
  218. d.IsValueType = t.IsValueType;
  219. if (t.IsGenericType)
  220. {
  221. d.IsGenericType = true;
  222. d.bt = t.GetGenericArguments()[0];
  223. }
  224. d.pt = t;
  225. d.Name = name;
  226. d.changeType = GetChangeType(t);
  227. d.Type = d_type;
  228. return d;
  229. }
  230. private Type GetChangeType(Type conversionType)
  231. {
  232. if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
  233. return Reflection.Instance.GetGenericArguments(conversionType)[0];
  234. return conversionType;
  235. }
  236. #region [ PROPERTY GET SET ]
  237. internal string GetTypeAssemblyName(Type t)
  238. {
  239. string val = "";
  240. if (_tyname.TryGetValue(t, out val))
  241. return val;
  242. else
  243. {
  244. string s = t.AssemblyQualifiedName;
  245. _tyname.Add(t, s);
  246. return s;
  247. }
  248. }
  249. internal Type GetTypeFromCache(string typename)
  250. {
  251. Type val = null;
  252. if (_typecache.TryGetValue(typename, out val))
  253. return val;
  254. else
  255. {
  256. Type t = Type.GetType(typename);
  257. //if (t == null) // RaptorDB : loading runtime assemblies
  258. //{
  259. // t = Type.GetType(typename, (name) => {
  260. // return AppDomain.CurrentDomain.GetAssemblies().Where(z => z.FullName == name.FullName).FirstOrDefault();
  261. // }, null, true);
  262. //}
  263. _typecache.Add(typename, t);
  264. return t;
  265. }
  266. }
  267. internal object FastCreateInstance(Type objtype)
  268. {
  269. try
  270. {
  271. CreateObject c = null;
  272. if (_constrcache.TryGetValue(objtype, out c))
  273. {
  274. return c();
  275. }
  276. else
  277. {
  278. if (objtype.IsClass)
  279. {
  280. DynamicMethod dynMethod = new DynamicMethod("_", objtype, null);
  281. ILGenerator ilGen = dynMethod.GetILGenerator();
  282. ilGen.Emit(OpCodes.Newobj, objtype.GetConstructor(Type.EmptyTypes));
  283. ilGen.Emit(OpCodes.Ret);
  284. c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
  285. _constrcache.Add(objtype, c);
  286. }
  287. else // structs
  288. {
  289. DynamicMethod dynMethod = new DynamicMethod("_", typeof(object), null);
  290. ILGenerator ilGen = dynMethod.GetILGenerator();
  291. var lv = ilGen.DeclareLocal(objtype);
  292. ilGen.Emit(OpCodes.Ldloca_S, lv);
  293. ilGen.Emit(OpCodes.Initobj, objtype);
  294. ilGen.Emit(OpCodes.Ldloc_0);
  295. ilGen.Emit(OpCodes.Box, objtype);
  296. ilGen.Emit(OpCodes.Ret);
  297. c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
  298. _constrcache.Add(objtype, c);
  299. }
  300. return c();
  301. }
  302. }
  303. catch (Exception exc)
  304. {
  305. throw new Exception(string.Format("Failed to fast create instance for type '{0}' from assembly '{1}'",
  306. objtype.FullName, objtype.AssemblyQualifiedName), exc);
  307. }
  308. }
  309. internal static GenericSetter CreateSetField(Type type, FieldInfo fieldInfo)
  310. {
  311. Type[] arguments = new Type[2];
  312. arguments[0] = arguments[1] = typeof(object);
  313. DynamicMethod dynamicSet = new DynamicMethod("_", typeof(object), arguments, type);
  314. ILGenerator il = dynamicSet.GetILGenerator();
  315. if (!type.IsClass) // structs
  316. {
  317. var lv = il.DeclareLocal(type);
  318. il.Emit(OpCodes.Ldarg_0);
  319. il.Emit(OpCodes.Unbox_Any, type);
  320. il.Emit(OpCodes.Stloc_0);
  321. il.Emit(OpCodes.Ldloca_S, lv);
  322. il.Emit(OpCodes.Ldarg_1);
  323. if (fieldInfo.FieldType.IsClass)
  324. il.Emit(OpCodes.Castclass, fieldInfo.FieldType);
  325. else
  326. il.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType);
  327. il.Emit(OpCodes.Stfld, fieldInfo);
  328. il.Emit(OpCodes.Ldloc_0);
  329. il.Emit(OpCodes.Box, type);
  330. il.Emit(OpCodes.Ret);
  331. }
  332. else
  333. {
  334. il.Emit(OpCodes.Ldarg_0);
  335. il.Emit(OpCodes.Ldarg_1);
  336. if (fieldInfo.FieldType.IsValueType)
  337. il.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType);
  338. il.Emit(OpCodes.Stfld, fieldInfo);
  339. il.Emit(OpCodes.Ldarg_0);
  340. il.Emit(OpCodes.Ret);
  341. }
  342. return (GenericSetter)dynamicSet.CreateDelegate(typeof(GenericSetter));
  343. }
  344. internal static GenericSetter CreateSetMethod(Type type, PropertyInfo propertyInfo)
  345. {
  346. MethodInfo setMethod = propertyInfo.GetSetMethod();
  347. if (setMethod == null)
  348. return null;
  349. Type[] arguments = new Type[2];
  350. arguments[0] = arguments[1] = typeof(object);
  351. DynamicMethod setter = new DynamicMethod("_", typeof(object), arguments);
  352. ILGenerator il = setter.GetILGenerator();
  353. if (!type.IsClass) // structs
  354. {
  355. var lv = il.DeclareLocal(type);
  356. il.Emit(OpCodes.Ldarg_0);
  357. il.Emit(OpCodes.Unbox_Any, type);
  358. il.Emit(OpCodes.Stloc_0);
  359. il.Emit(OpCodes.Ldloca_S, lv);
  360. il.Emit(OpCodes.Ldarg_1);
  361. if (propertyInfo.PropertyType.IsClass)
  362. il.Emit(OpCodes.Castclass, propertyInfo.PropertyType);
  363. else
  364. il.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
  365. il.EmitCall(OpCodes.Call, setMethod, null);
  366. il.Emit(OpCodes.Ldloc_0);
  367. il.Emit(OpCodes.Box, type);
  368. }
  369. else
  370. {
  371. if (!setMethod.IsStatic)
  372. {
  373. il.Emit(OpCodes.Ldarg_0);
  374. il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
  375. il.Emit(OpCodes.Ldarg_1);
  376. if (propertyInfo.PropertyType.IsClass)
  377. il.Emit(OpCodes.Castclass, propertyInfo.PropertyType);
  378. else
  379. il.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
  380. il.EmitCall(OpCodes.Callvirt, setMethod, null);
  381. il.Emit(OpCodes.Ldarg_0);
  382. }
  383. else
  384. {
  385. il.Emit(OpCodes.Ldarg_0);
  386. il.Emit(OpCodes.Ldarg_1);
  387. if (propertyInfo.PropertyType.IsClass)
  388. il.Emit(OpCodes.Castclass, propertyInfo.PropertyType);
  389. else
  390. il.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
  391. il.Emit(OpCodes.Call, setMethod);
  392. }
  393. }
  394. il.Emit(OpCodes.Ret);
  395. return (GenericSetter)setter.CreateDelegate(typeof(GenericSetter));
  396. }
  397. internal static GenericGetter CreateGetField(Type type, FieldInfo fieldInfo)
  398. {
  399. DynamicMethod dynamicGet = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type);
  400. ILGenerator il = dynamicGet.GetILGenerator();
  401. if (!type.IsClass) // structs
  402. {
  403. var lv = il.DeclareLocal(type);
  404. il.Emit(OpCodes.Ldarg_0);
  405. il.Emit(OpCodes.Unbox_Any, type);
  406. il.Emit(OpCodes.Stloc_0);
  407. il.Emit(OpCodes.Ldloca_S, lv);
  408. il.Emit(OpCodes.Ldfld, fieldInfo);
  409. if (fieldInfo.FieldType.IsValueType)
  410. il.Emit(OpCodes.Box, fieldInfo.FieldType);
  411. }
  412. else
  413. {
  414. il.Emit(OpCodes.Ldarg_0);
  415. il.Emit(OpCodes.Ldfld, fieldInfo);
  416. if (fieldInfo.FieldType.IsValueType)
  417. il.Emit(OpCodes.Box, fieldInfo.FieldType);
  418. }
  419. il.Emit(OpCodes.Ret);
  420. return (GenericGetter)dynamicGet.CreateDelegate(typeof(GenericGetter));
  421. }
  422. internal static GenericGetter CreateGetMethod(Type type, PropertyInfo propertyInfo)
  423. {
  424. MethodInfo getMethod = propertyInfo.GetGetMethod();
  425. if (getMethod == null)
  426. return null;
  427. DynamicMethod getter = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type);
  428. ILGenerator il = getter.GetILGenerator();
  429. if (!type.IsClass) // structs
  430. {
  431. var lv = il.DeclareLocal(type);
  432. il.Emit(OpCodes.Ldarg_0);
  433. il.Emit(OpCodes.Unbox_Any, type);
  434. il.Emit(OpCodes.Stloc_0);
  435. il.Emit(OpCodes.Ldloca_S, lv);
  436. il.EmitCall(OpCodes.Call, getMethod, null);
  437. if (propertyInfo.PropertyType.IsValueType)
  438. il.Emit(OpCodes.Box, propertyInfo.PropertyType);
  439. }
  440. else
  441. {
  442. if (!getMethod.IsStatic)
  443. {
  444. il.Emit(OpCodes.Ldarg_0);
  445. il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
  446. il.EmitCall(OpCodes.Callvirt, getMethod, null);
  447. }
  448. else
  449. il.Emit(OpCodes.Call, getMethod);
  450. if (propertyInfo.PropertyType.IsValueType)
  451. il.Emit(OpCodes.Box, propertyInfo.PropertyType);
  452. }
  453. il.Emit(OpCodes.Ret);
  454. return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
  455. }
  456. internal Getters[] GetGetters(Type type, bool ShowReadOnlyProperties, List<Type> IgnoreAttributes)
  457. {
  458. Getters[] val = null;
  459. if (_getterscache.TryGetValue(type, out val))
  460. return val;
  461. //bool isAnonymous = IsAnonymousType(type);
  462. var bf = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
  463. //if (ShowReadOnlyProperties)
  464. // bf |= BindingFlags.NonPublic;
  465. PropertyInfo[] props = type.GetProperties(bf);
  466. List<Getters> getters = new List<Getters>();
  467. foreach (PropertyInfo p in props)
  468. {
  469. if (p.GetIndexParameters().Length > 0)
  470. {// Property is an indexer
  471. continue;
  472. }
  473. if (!p.CanWrite && (ShowReadOnlyProperties == false))//|| isAnonymous == false))
  474. continue;
  475. if (IgnoreAttributes != null)
  476. {
  477. bool found = false;
  478. foreach (var ignoreAttr in IgnoreAttributes)
  479. {
  480. if (p.IsDefined(ignoreAttr, false))
  481. {
  482. found = true;
  483. break;
  484. }
  485. }
  486. if (found)
  487. continue;
  488. }
  489. GenericGetter g = CreateGetMethod(type, p);
  490. if (g != null)
  491. getters.Add(new Getters { Getter = g, Name = p.Name, lcName = p.Name.ToLower() });
  492. }
  493. FieldInfo[] fi = type.GetFields(bf);
  494. foreach (var f in fi)
  495. {
  496. if (IgnoreAttributes != null)
  497. {
  498. bool found = false;
  499. foreach (var ignoreAttr in IgnoreAttributes)
  500. {
  501. if (f.IsDefined(ignoreAttr, false))
  502. {
  503. found = true;
  504. break;
  505. }
  506. }
  507. if (found)
  508. continue;
  509. }
  510. if (f.IsLiteral == false)
  511. {
  512. GenericGetter g = CreateGetField(type, f);
  513. if (g != null)
  514. getters.Add(new Getters { Getter = g, Name = f.Name, lcName = f.Name.ToLower() });
  515. }
  516. }
  517. val = getters.ToArray();
  518. _getterscache.Add(type, val);
  519. return val;
  520. }
  521. //private static bool IsAnonymousType(Type type)
  522. //{
  523. // // may break in the future if compiler defined names change...
  524. // const string CS_ANONYMOUS_PREFIX = "<>f__AnonymousType";
  525. // const string VB_ANONYMOUS_PREFIX = "VB$AnonymousType";
  526. // if (type == null)
  527. // throw new ArgumentNullException("type");
  528. // if (type.Name.StartsWith(CS_ANONYMOUS_PREFIX, StringComparison.Ordinal) || type.Name.StartsWith(VB_ANONYMOUS_PREFIX, StringComparison.Ordinal))
  529. // {
  530. // return type.IsDefined(typeof(CompilerGeneratedAttribute), false);
  531. // }
  532. // return false;
  533. //}
  534. #endregion
  535. internal void ResetPropertyCache()
  536. {
  537. _propertycache = new SafeDictionary<string, Dictionary<string, myPropInfo>>();
  538. }
  539. internal void ClearReflectionCache()
  540. {
  541. _tyname = new SafeDictionary<Type, string>();
  542. _typecache = new SafeDictionary<string, Type>();
  543. _constrcache = new SafeDictionary<Type, CreateObject>();
  544. _getterscache = new SafeDictionary<Type, Getters[]>();
  545. _propertycache = new SafeDictionary<string, Dictionary<string, myPropInfo>>();
  546. _genericTypes = new SafeDictionary<Type, Type[]>();
  547. _genericTypeDef = new SafeDictionary<Type, Type>();
  548. }
  549. }
  550. }