DynamicBuilderHelper.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection.Emit;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace SqlSugar
  9. {
  10. public static class DynamicBuilderHelper
  11. {
  12. public static Type CreateDynamicClass(string className, List<PropertyMetadata> properties, TypeAttributes attributes = TypeAttributes.Public, List<CustomAttributeBuilder> classCustomAttributes = null, Type baseType = null, Type[] interfaces = null)
  13. {
  14. TypeBuilder typeBuilder = EmitTool.CreateTypeBuilder(className, attributes, baseType, interfaces);
  15. if (classCustomAttributes != null)
  16. {
  17. foreach (var attributeBuilder in classCustomAttributes)
  18. {
  19. typeBuilder.SetCustomAttribute(attributeBuilder);
  20. }
  21. }
  22. foreach (PropertyMetadata property in properties)
  23. {
  24. var type = property.Type;
  25. if (type == typeof(DynamicOneselfType))
  26. {
  27. type = typeBuilder;
  28. }
  29. else if (type == typeof(DynamicOneselfTypeList))
  30. {
  31. type = typeof(List<>).MakeGenericType(typeBuilder);
  32. }
  33. EmitTool.CreateProperty(typeBuilder, property.Name, type, property.CustomAttributes);
  34. }
  35. Type dynamicType = typeBuilder.CreateTypeInfo().AsType();
  36. return dynamicType;
  37. }
  38. }
  39. }