Beispiel #1
0
        internal static YamlNode TypeToNode(object obj)
        {
            // special snowflake string
            if (obj is string s)
            {
                return(s);
            }

            var type = obj.GetType();

            // val primitives and val enums
            if (type.IsPrimitive || type == typeof(Enum))
            {
                return(obj.ToString());
            }

            // custom TypeSerializer
            if (_typeSerializers.TryGetValue(type, out var serializer))
            {
                return(serializer.TypeToNode(obj));
            }

            // other val (struct)
            if (type.IsValueType)
            {
                return(_structSerializer.TypeToNode(obj));
            }

            throw new ArgumentException($"Type {type.FullName} is not supported.", nameof(obj));
        }
Beispiel #2
0
        internal static YamlNode TypeToNode(object obj)
        {
            // special snowflake string
            if (obj is string s)
            {
                return(s);
            }

            var type = obj.GetType();

            // val primitives and val enums
            if (type.IsPrimitive || type == typeof(Enum))
            {
                return(obj.ToString());
            }

            // List<T>
            if (TryGenericListType(type, out var listType))
            {
                var node = new YamlSequenceNode();

                foreach (var entry in (IEnumerable)obj)
                {
                    var entryNode = TypeToNode(entry);
                    node.Add(entryNode);
                }

                return(node);
            }

            // Dictionary<K,V>
            if (TryGenericDictType(type, out var keyType, out var valType))
            {
                var node = new YamlMappingNode();

                foreach (DictionaryEntry entry in (IDictionary)obj)
                {
                    var keyNode = TypeToNode(entry.Key);
                    var valNode = TypeToNode(entry.Value);

                    node.Add(keyNode, valNode);
                }

                return(node);
            }

            // custom TypeSerializer
            if (_typeSerializers.TryGetValue(type, out var serializer))
            {
                return(serializer.TypeToNode(obj));
            }

            // other val (struct)
            if (type.IsValueType)
            {
                return(_structSerializer.TypeToNode(obj));
            }

            // ref type that isn't a custom TypeSerializer
            throw new ArgumentException($"Type {type.FullName} is not supported.", nameof(obj));
        }