GenericClass.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using dnlib.DotNet;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. namespace HybridCLR.Editor.Meta
  6. {
  7. public class GenericClass
  8. {
  9. public TypeDef Type { get; }
  10. public List<TypeSig> KlassInst { get; }
  11. private readonly int _hashCode;
  12. public GenericClass(TypeDef type, List<TypeSig> classInst)
  13. {
  14. Type = type;
  15. KlassInst = classInst;
  16. _hashCode = ComputHashCode();
  17. }
  18. public GenericClass ToGenericShare()
  19. {
  20. return new GenericClass(Type, MetaUtil.ToShareTypeSigs(Type.Module.CorLibTypes, KlassInst));
  21. }
  22. public override bool Equals(object obj)
  23. {
  24. if (obj is GenericClass gc)
  25. {
  26. return Type == gc.Type && MetaUtil.EqualsTypeSigArray(KlassInst, gc.KlassInst);
  27. }
  28. return false;
  29. }
  30. public override int GetHashCode()
  31. {
  32. return _hashCode;
  33. }
  34. private int ComputHashCode()
  35. {
  36. int hash = TypeEqualityComparer.Instance.GetHashCode(Type);
  37. if (KlassInst != null)
  38. {
  39. hash = HashUtil.CombineHash(hash, HashUtil.ComputHash(KlassInst));
  40. }
  41. return hash;
  42. }
  43. public TypeSig ToTypeSig()
  44. {
  45. return new GenericInstSig(this.Type.ToTypeSig().ToClassOrValueTypeSig(), this.KlassInst);
  46. }
  47. public static GenericClass ResolveClass(TypeSpec type, GenericArgumentContext ctx)
  48. {
  49. var sig = type.TypeSig.ToGenericInstSig();
  50. if (sig == null)
  51. {
  52. return null;
  53. }
  54. TypeDef def = type.ResolveTypeDef();
  55. if (def == null)
  56. {
  57. Debug.LogWarning($"type:{type} ResolveTypeDef() == null");
  58. return null;
  59. }
  60. var klassInst = ctx != null ? sig.GenericArguments.Select(ga => MetaUtil.Inflate(ga, ctx)).ToList() : sig.GenericArguments.ToList();
  61. return new GenericClass(def, klassInst);
  62. }
  63. }
  64. }