目前没有办法从 a 反序列YamlNode
化,您的方法是可能的解决方法之一。如果您想避免将节点写入缓冲区,您可以实现IParser
从 a 读取的接口YamlNode
,例如这个示例。
我在上面的示例中执行此操作的方式是创建一个将 a 转换为 a 的YamlNode
适配器IRnumerable<ParsingEvent>
:
public static class YamlNodeToEventStreamConverter
{
public static IEnumerable<ParsingEvent> ConvertToEventStream(YamlStream stream)
{
yield return new StreamStart();
foreach (var document in stream.Documents)
{
foreach (var evt in ConvertToEventStream(document))
{
yield return evt;
}
}
yield return new StreamEnd();
}
public static IEnumerable<ParsingEvent> ConvertToEventStream(YamlDocument document)
{
yield return new DocumentStart();
foreach (var evt in ConvertToEventStream(document.RootNode))
{
yield return evt;
}
yield return new DocumentEnd(false);
}
public static IEnumerable<ParsingEvent> ConvertToEventStream(YamlNode node)
{
var scalar = node as YamlScalarNode;
if (scalar != null)
{
return ConvertToEventStream(scalar);
}
var sequence = node as YamlSequenceNode;
if (sequence != null)
{
return ConvertToEventStream(sequence);
}
var mapping = node as YamlMappingNode;
if (mapping != null)
{
return ConvertToEventStream(mapping);
}
throw new NotSupportedException(string.Format("Unsupported node type: {0}", node.GetType().Name));
}
private static IEnumerable<ParsingEvent> ConvertToEventStream(YamlScalarNode scalar)
{
yield return new Scalar(scalar.Anchor, scalar.Tag, scalar.Value, scalar.Style, false, false);
}
private static IEnumerable<ParsingEvent> ConvertToEventStream(YamlSequenceNode sequence)
{
yield return new SequenceStart(sequence.Anchor, sequence.Tag, false, sequence.Style);
foreach (var node in sequence.Children)
{
foreach (var evt in ConvertToEventStream(node))
{
yield return evt;
}
}
yield return new SequenceEnd();
}
private static IEnumerable<ParsingEvent> ConvertToEventStream(YamlMappingNode mapping)
{
yield return new MappingStart(mapping.Anchor, mapping.Tag, false, mapping.Style);
foreach (var pair in mapping.Children)
{
foreach (var evt in ConvertToEventStream(pair.Key))
{
yield return evt;
}
foreach (var evt in ConvertToEventStream(pair.Value))
{
yield return evt;
}
}
yield return new MappingEnd();
}
}
一旦你有了这个,创建一个适配器就很简单了IParser
,因为这两个接口基本上是等价的:
public class EventStreamParserAdapter : IParser
{
private readonly IEnumerator<ParsingEvent> enumerator;
public EventStreamParserAdapter(IEnumerable<ParsingEvent> events)
{
enumerator = events.GetEnumerator();
}
public ParsingEvent Current
{
get
{
return enumerator.Current;
}
}
public bool MoveNext()
{
return enumerator.MoveNext();
}
}
YamlStream
然后,您可以使用适配器从任何YamlDocument
或反序列化YamlNode
:
var stream = new YamlStream();
stream.Load(new StringReader(input));
var deserializer = new DeserializerBuilder()
.WithNamingConvention(new CamelCaseNamingConvention())
.Build();
var prefs = deserializer.Deserialize<YOUR_TYPE>(
new EventStreamParserAdapter(
YamlNodeToEventStreamConverter.ConvertToEventStream(stream)
)
);