Initializes the object fields and properties with their default values based on . The object.
(object obj)
| 787 | /// </summary> |
| 788 | /// <param name="obj">The object.</param> |
| 789 | public static void InitDefaultValues(object obj) |
| 790 | { |
| 791 | var scriptType = TypeUtils.GetObjectType(obj); |
| 792 | if (!scriptType) |
| 793 | return; |
| 794 | var isStructure = scriptType.IsStructure; |
| 795 | |
| 796 | var fields = scriptType.GetFields(BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public); |
| 797 | for (var i = 0; i < fields.Length; i++) |
| 798 | { |
| 799 | var field = fields[i]; |
| 800 | var attr = field.GetAttribute<System.ComponentModel.DefaultValueAttribute>(); |
| 801 | if (attr != null) |
| 802 | { |
| 803 | // Prevent value type conflicts |
| 804 | var value = attr.Value; |
| 805 | var fieldType = field.ValueType.Type; |
| 806 | if (value != null && value.GetType() != fieldType) |
| 807 | value = Convert.ChangeType(value, fieldType); |
| 808 | |
| 809 | field.SetValue(obj, value); |
| 810 | } |
| 811 | else if (isStructure) |
| 812 | { |
| 813 | // C# doesn't support default values for structure members so initialize them |
| 814 | field.SetValue(obj, TypeUtils.GetDefaultValue(field.ValueType)); |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | var properties = scriptType.GetProperties(BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public); |
| 819 | for (var i = 0; i < properties.Length; i++) |
| 820 | { |
| 821 | var property = properties[i]; |
| 822 | var attr = property.GetAttribute<System.ComponentModel.DefaultValueAttribute>(); |
| 823 | if (attr != null) |
| 824 | { |
| 825 | // Prevent value type conflicts |
| 826 | var value = attr.Value; |
| 827 | var propertyType = property.ValueType.Type; |
| 828 | if (value != null && value.GetType() != propertyType) |
| 829 | value = Convert.ChangeType(value, propertyType); |
| 830 | |
| 831 | property.SetValue(obj, value); |
| 832 | } |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | /// <summary> |
| 837 | /// Gets the property name for UI. Removes unnecessary characters and filters text. Makes it more user-friendly. |
no test coverage detected