本文整理汇总了C#中EventReader.Expect方法的典型用法代码示例。如果您正苦于以下问题:C# EventReader.Expect方法的具体用法?C# EventReader.Expect怎么用?C# EventReader.Expect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类EventReader
的用法示例。
在下文中一共展示了EventReader.Expect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: while
bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, out object value)
{
if (!typeof(IList).IsAssignableFrom(expectedType))
{
value = false;
return false;
}
reader.Expect<SequenceStart>();
var list = (IList)_objectFactory.Create(expectedType);
while (!reader.Accept<SequenceEnd>())
{
var item = nestedObjectDeserializer(reader, typeof(object));
var promise = item as IValuePromise;
if (promise == null)
{
list.Add(item);
}
else
{
var index = list.Count;
list.Add(null);
promise.ValueAvailable += v => list[index] = v;
}
}
value = list;
reader.Expect<SequenceEnd>();
return true;
}
示例2: YamlDocument
/// <summary>
/// Initializes a new instance of the <see cref="YamlDocument"/> class.
/// </summary>
/// <param name="events">The events.</param>
internal YamlDocument(EventReader events)
{
DocumentLoadingState state = new DocumentLoadingState();
events.Expect<DocumentStart>();
while (!events.Accept<DocumentEnd>())
{
Debug.Assert(RootNode == null);
RootNode = YamlNode.ParseNode(events, state);
if (RootNode is YamlAliasNode)
{
throw new YamlException();
}
}
state.ResolveAliases();
#if DEBUG
foreach (var node in AllNodes)
{
if (node is YamlAliasNode)
{
throw new InvalidOperationException("Error in alias resolution.");
}
}
#endif
events.Expect<DocumentEnd>();
}
示例3: Start
// Use this for initialization
void Start () {
var input = new StringReader(Document);
var deserializer = new Deserializer();
var reader = new EventReader(new Parser(input));
// Consume the stream start event "manually"
reader.Expect<StreamStart>();
var output = new StringBuilder();
while(reader.Accept<DocumentStart>())
{
// Deserialize the document
var doc = deserializer.Deserialize<List<string>>(reader);
output.AppendLine("## Document");
foreach(var item in doc)
{
output.AppendLine(item);
}
}
Debug.Log(output);
}
示例4: YamlScalarNode
/// <summary>
/// Initializes a new instance of the <see cref="YamlScalarNode"/> class.
/// </summary>
/// <param name="events">The events.</param>
/// <param name="state">The state.</param>
internal YamlScalarNode(EventReader events, DocumentLoadingState state)
{
Scalar scalar = events.Expect<Scalar>();
Load(scalar, state);
Value = scalar.Value;
Style = scalar.Style;
}
示例5: GetData
private static object GetData(EventReader r)
{
if(r.Accept<Scalar>())
{
return r.Expect<Scalar>().Value;
}
else if(r.Accept<SequenceStart>()) {
var seq = new ArrayList();
r.Expect<SequenceStart>();
while(!r.Accept<SequenceEnd>())
{
seq.Add(GetData(r));
}
r.Expect<SequenceEnd>();
// Arrays are IStructuralEquatable, ArrayLists are not.
return seq.ToArray();
}
else if(r.Accept<MappingStart>())
{
// Since we use sequences as keys...
var map = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer);
r.Expect<MappingStart>();
while(!r.Accept<MappingEnd>())
{
object key = GetData(r);
object value = GetData(r);
map.Add(key, value);
}
r.Expect<MappingEnd>();
return map;
}
else {
throw new YamlException();
}
}
示例6: while
bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, out object value)
{
var mapping = reader.Allow<MappingStart>();
if (mapping == null)
{
value = null;
return false;
}
value = _objectFactory.Create(expectedType);
while (!reader.Accept<MappingEnd>())
{
var propertyName = reader.Expect<Scalar>();
var property = _typeDescriptor.GetProperty(expectedType, null, propertyName.Value, _ignoreUnmatched);
if (property == null)
{
reader.SkipThisAndNestedEvents();
continue;
}
var propertyValue = nestedObjectDeserializer(reader, property.Type);
var propertyValuePromise = propertyValue as IValuePromise;
if (propertyValuePromise == null)
{
var convertedValue = TypeConverter.ChangeType(propertyValue, property.Type);
property.Write(value, convertedValue);
}
else
{
var valueRef = value;
propertyValuePromise.ValueAvailable += v =>
{
var convertedValue = TypeConverter.ChangeType(v, property.Type);
property.Write(valueRef, convertedValue);
};
}
}
reader.Expect<MappingEnd>();
return true;
}
示例7: ReadConfigYAML
public static void ReadConfigYAML()
{
var input = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + @"/AME.yaml");
var deserializer = new Deserializer();
var reader = new EventReader(new Parser(input));
// Deserialize the document
reader.Expect<StreamStart>();
reader.Accept<DocumentStart>();
var settings = deserializer.Deserialize<AMESettings>(reader);
reader.Accept<DocumentStart>();
var behaviorManifests = deserializer.Deserialize<BehaviorManifests>(reader);
foreach (var behavior in behaviorManifests.FRLGBehaviors)
{
if(behavior.Value[0] == '&')
behaviorManifests.FRLGBehaviors[behavior.Key] = InternalStrings.ResourceManager.GetString(behavior.Value);
Console.WriteLine("[{0}] {1}", behavior.Key.ToString("X"), behavior.Value);
}
}
示例8: Main
static void Main(string[] args)
{
OrderedDictionary zones;
using (var sr = new StreamReader(args[0]))
{
var parser = new Parser(sr);
var er = new EventReader(parser);
er.Expect<StreamStart>();
er.Expect<DocumentStart>();
zones = (OrderedDictionary)GetData(er);
er.Expect<DocumentEnd>();
er.Expect<StreamEnd>();
}
// Remove modelsets key, not a real zone
zones.Remove("modelsets");
// Generate the C# structures
//
// We want a command dictionary that does not include the model data, which we
// are not using.
var commands = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer);
foreach (DictionaryEntry zoneEntry in zones)
{
object zone = zoneEntry.Key;
OrderedDictionary commandsInZone = (OrderedDictionary)zoneEntry.Value;
OrderedDictionary newCommands = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer);
foreach (DictionaryEntry commandEntry in commandsInZone)
{
object command = commandEntry.Key;
OrderedDictionary commandData = (OrderedDictionary)commandEntry.Value;
OrderedDictionary values = (OrderedDictionary)commandData["values"];
OrderedDictionary newValues = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer);
foreach (DictionaryEntry valueEntry in values)
{
object value = valueEntry.Key;
OrderedDictionary valueData = (OrderedDictionary)valueEntry.Value;
OrderedDictionary newValueData = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer)
{
{ "name", valueData["name"] },
{ "description", valueData["description"] }
};
newValues.Add(value, newValueData);
}
OrderedDictionary newCommandData = new OrderedDictionary(StructuralComparisons.StructuralEqualityComparer)
{
{ "name", commandData["name"] },
{ "description", commandData["description"] },
{ "values", newValues }
};
newCommands.Add(command, newCommandData);
}
commands.Add(zone, newCommands);
}
var zoneMappings = new OrderedDictionary()
{
// use main as default zone
{ "", "main" }
};
var commandMappings = Odict(
from DictionaryEntry zoneEntry in zones
select new DictionaryEntry
{
Key = zoneEntry.Key,
Value = Odict(FindCommandAliases((OrderedDictionary)zoneEntry.Value))
}
);
var valueMappings = Odict(
from DictionaryEntry zoneEntry in zones
let zone = zoneEntry.Key
let commands_ = zoneEntry.Value
select new DictionaryEntry
{
Key = zone,
Value = Odict(
from DictionaryEntry commandEntry in (IEnumerable)commands_
let command = commandEntry.Key
let commandData = commandEntry.Value
select new DictionaryEntry
{
Key = command,
Value = Odict( FindValueAliases((OrderedDictionary)(commandData as IDictionary)["values"]) )
}
)
}
);
Console.OutputEncoding = Encoding.UTF8;
//.........这里部分代码省略.........
示例9: Deserialize
/// <summary>
/// Deserializes an object of the specified type.
/// </summary>
/// <param name="reader">The <see cref="EventReader" /> where to deserialize the object.</param>
/// <param name="type">The static type of the object to deserialize.</param>
/// <param name="options">Options that control how the deserialization is to be performed.</param>
/// <returns>Returns the deserialized object.</returns>
public object Deserialize(EventReader reader, Type type, DeserializationOptions options = DeserializationOptions.None)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
var hasStreamStart = reader.Allow<StreamStart>() != null;
var hasDocumentStart = reader.Allow<DocumentStart>() != null;
if (hasDocumentStart)
{
reader.Expect<DocumentEnd>();
}
if (hasStreamStart)
{
reader.Expect<StreamEnd>();
}
}
示例10: ParseNode
/// <summary>
/// Parses the node represented by the next event in <paramref name="events" />.
/// </summary>
/// <param name="events">The events.</param>
/// <param name="state">The state.</param>
/// <returns>Returns the node that has been parsed.</returns>
internal static YamlNode ParseNode(EventReader events, DocumentLoadingState state)
{
if (events.Accept<Scalar>())
{
return new YamlScalarNode(events, state);
}
if (events.Accept<SequenceStart>())
{
return new YamlSequenceNode(events, state);
}
if (events.Accept<MappingStart>())
{
return new YamlMappingNode(events, state);
}
if (events.Accept<AnchorAlias>())
{
AnchorAlias alias = events.Expect<AnchorAlias>();
return state.GetNode(alias.Value, false, alias.Start, alias.End) ?? new YamlAliasNode(alias.Value);
}
throw new ArgumentException("The current event is of an unsupported type.", "events");
}
示例11: DeserializeHelper
private static void DeserializeHelper(Type tKey, Type tValue, EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, IDictionary result)
{
reader.Expect<MappingStart>();
while (!reader.Accept<MappingEnd>())
{
var key = nestedObjectDeserializer(reader, tKey);
var keyPromise = key as IValuePromise;
var value = nestedObjectDeserializer(reader, tValue);
var valuePromise = value as IValuePromise;
if (keyPromise == null)
{
if (valuePromise == null)
{
// Happy path: both key and value are known
result[key] = value;
}
else
{
// Key is known, value is pending
valuePromise.ValueAvailable += v => result[key] = v;
}
}
else
{
if (valuePromise == null)
{
// Key is pending, value is known
keyPromise.ValueAvailable += v => result[v] = value;
}
else
{
// Both key and value are pending. We need to wait until both of them becom available.
var hasFirstPart = false;
keyPromise.ValueAvailable += v =>
{
if (hasFirstPart)
{
result[v] = value;
}
else
{
key = v;
hasFirstPart = true;
}
};
valuePromise.ValueAvailable += v =>
{
if (hasFirstPart)
{
result[key] = v;
}
else
{
value = v;
hasFirstPart = true;
}
};
}
}
}
reader.Expect<MappingEnd>();
}
示例12: DeserializeValue
private object DeserializeValue(EventReader reader, Type expectedType, object context)
{
if (reader.Accept<AnchorAlias>())
{
throw new NotImplementedException();
//return context.Anchors[reader.Expect<AnchorAlias>().Value];
}
var nodeEvent = (NodeEvent)reader.Parser.Current;
if (IsNull(nodeEvent))
{
reader.Expect<NodeEvent>();
AddAnchoredObject(nodeEvent, null, context.Anchors);
return null;
}
object result = DeserializeValueNotNull(reader, context, nodeEvent, expectedType);
return ObjectConverter.Convert(result, expectedType);
}
示例13: MigrateAssetIfNeeded
public static bool MigrateAssetIfNeeded(AssetMigrationContext context, PackageLoadingAssetFile loadAsset)
{
var assetFullPath = loadAsset.FilePath.FullPath;
// Determine if asset was Yaml or not
var assetFileExtension = Path.GetExtension(assetFullPath);
if (assetFileExtension == null)
return false;
assetFileExtension = assetFileExtension.ToLowerInvariant();
var serializer = AssetSerializer.FindSerializer(assetFileExtension);
if (!(serializer is AssetYamlSerializer))
return false;
// We've got a Yaml asset, let's get expected and serialized versions
var serializedVersion = 0;
int expectedVersion;
Type assetType;
// Read from Yaml file the asset version and its type (to get expected version)
// Note: It tries to read as few as possible (SerializedVersion is expected to be right after Id, so it shouldn't try to read further than that)
using (var assetStream = loadAsset.OpenStream())
using (var streamReader = new StreamReader(assetStream))
{
var yamlEventReader = new EventReader(new Parser(streamReader));
// Skip header
yamlEventReader.Expect<StreamStart>();
yamlEventReader.Expect<DocumentStart>();
var mappingStart = yamlEventReader.Expect<MappingStart>();
var yamlSerializerSettings = YamlSerializer.GetSerializerSettings();
var tagTypeRegistry = yamlSerializerSettings.TagTypeRegistry;
bool typeAliased;
assetType = tagTypeRegistry.TypeFromTag(mappingStart.Tag, out typeAliased);
expectedVersion = AssetRegistry.GetCurrentFormatVersion(assetType);
Scalar assetKey;
while ((assetKey = yamlEventReader.Allow<Scalar>()) != null)
{
// Only allow Id before SerializedVersion
if (assetKey.Value == "Id")
{
yamlEventReader.Skip();
continue;
}
if (assetKey.Value == "SerializedVersion")
{
serializedVersion = Convert.ToInt32(yamlEventReader.Expect<Scalar>().Value, CultureInfo.InvariantCulture);
break;
}
}
}
if (serializedVersion > expectedVersion)
{
// Try to open an asset newer than what we support (probably generated by a newer Paradox)
throw new InvalidOperationException(string.Format("Asset of type {0} has been serialized with newer version {1}, but only version {2} is supported. Was this asset created with a newer version of Paradox?", assetType, serializedVersion, expectedVersion));
}
if (serializedVersion < expectedVersion)
{
// Perform asset upgrade
context.Log.Verbose("{0} needs update, from version {1} to version {2}", Path.GetFullPath(assetFullPath), serializedVersion, expectedVersion);
// transform the stream into string.
string assetAsString;
using (var assetStream = loadAsset.OpenStream())
using (var assetStreamReader = new StreamReader(assetStream, Encoding.UTF8))
{
assetAsString = assetStreamReader.ReadToEnd();
}
// Load the asset as a YamlNode object
var input = new StringReader(assetAsString);
var yamlStream = new YamlStream();
yamlStream.Load(input);
var yamlRootNode = (YamlMappingNode)yamlStream.Documents[0].RootNode;
// Check if there is any asset updater
var assetUpgraders = AssetRegistry.GetAssetUpgraders(assetType);
if (assetUpgraders == null)
{
throw new InvalidOperationException(string.Format("Asset of type {0} should be updated from version {1} to {2}, but no asset migration path was found", assetType, serializedVersion, expectedVersion));
}
// Instantiate asset updaters
var currentVersion = serializedVersion;
while (currentVersion != expectedVersion)
{
int targetVersion;
// This will throw an exception if no upgrader is available for the given version, exiting the loop in case of error.
var upgrader = assetUpgraders.GetUpgrader(currentVersion, out targetVersion);
upgrader.Upgrade(context, currentVersion, targetVersion, yamlRootNode, loadAsset);
currentVersion = targetVersion;
}
// Make sure asset is updated to latest version
//.........这里部分代码省略.........
示例14: MigrateAssetIfNeeded
public static bool MigrateAssetIfNeeded(AssetMigrationContext context, PackageLoadingAssetFile loadAsset, string dependencyName, PackageVersion untilVersion = null)
{
var assetFullPath = loadAsset.FilePath.FullPath;
// Determine if asset was Yaml or not
var assetFileExtension = Path.GetExtension(assetFullPath);
if (assetFileExtension == null)
return false;
assetFileExtension = assetFileExtension.ToLowerInvariant();
var serializer = AssetFileSerializer.FindSerializer(assetFileExtension);
if (!(serializer is YamlAssetSerializer))
return false;
// We've got a Yaml asset, let's get expected and serialized versions
var serializedVersion = PackageVersion.Zero;
PackageVersion expectedVersion;
Type assetType;
// Read from Yaml file the asset version and its type (to get expected version)
// Note: It tries to read as few as possible (SerializedVersion is expected to be right after Id, so it shouldn't try to read further than that)
using (var assetStream = loadAsset.OpenStream())
using (var streamReader = new StreamReader(assetStream))
{
var yamlEventReader = new EventReader(new Parser(streamReader));
// Skip header
yamlEventReader.Expect<StreamStart>();
yamlEventReader.Expect<DocumentStart>();
var mappingStart = yamlEventReader.Expect<MappingStart>();
var tagTypeRegistry = AssetYamlSerializer.Default.GetSerializerSettings().TagTypeRegistry;
bool typeAliased;
assetType = tagTypeRegistry.TypeFromTag(mappingStart.Tag, out typeAliased);
var expectedVersions = AssetRegistry.GetCurrentFormatVersions(assetType);
expectedVersion = expectedVersions?.FirstOrDefault(x => x.Key == dependencyName).Value ?? PackageVersion.Zero;
Scalar assetKey;
while ((assetKey = yamlEventReader.Allow<Scalar>()) != null)
{
// Only allow Id before SerializedVersion
if (assetKey.Value == nameof(Asset.Id))
{
yamlEventReader.Skip();
}
else if (assetKey.Value == nameof(Asset.SerializedVersion))
{
// Check for old format: only a scalar
var scalarVersion = yamlEventReader.Allow<Scalar>();
if (scalarVersion != null)
{
serializedVersion = PackageVersion.Parse("0.0." + Convert.ToInt32(scalarVersion.Value, CultureInfo.InvariantCulture));
// Let's update to new format
using (var yamlAsset = loadAsset.AsYamlAsset())
{
yamlAsset.DynamicRootNode.RemoveChild(nameof(Asset.SerializedVersion));
AssetUpgraderBase.SetSerializableVersion(yamlAsset.DynamicRootNode, dependencyName, serializedVersion);
var baseBranch = yamlAsset.DynamicRootNode["~Base"];
if (baseBranch != null)
{
var baseAsset = baseBranch["Asset"];
if (baseAsset != null)
{
baseAsset.RemoveChild(nameof(Asset.SerializedVersion));
AssetUpgraderBase.SetSerializableVersion(baseAsset, dependencyName, serializedVersion);
}
}
}
}
else
{
// New format: package => version mapping
yamlEventReader.Expect<MappingStart>();
while (!yamlEventReader.Accept<MappingEnd>())
{
var packageName = yamlEventReader.Expect<Scalar>().Value;
var packageVersion = PackageVersion.Parse(yamlEventReader.Expect<Scalar>().Value);
// For now, we handle only one dependency at a time
if (packageName == dependencyName)
{
serializedVersion = packageVersion;
}
}
yamlEventReader.Expect<MappingEnd>();
}
break;
}
else
{
// If anything else than Id or SerializedVersion, let's stop
break;
}
}
//.........这里部分代码省略.........
示例15: while
bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func<EventReader, Type, object> nestedObjectDeserializer, out object value)
{
if(!typeof(IDictionary).IsAssignableFrom(expectedType))
{
value = false;
return false;
}
reader.Expect<MappingStart>();
var dictionary = (IDictionary)_objectFactory.Create(expectedType);
while (!reader.Accept<MappingEnd>())
{
var key = nestedObjectDeserializer(reader, typeof(object));
var keyPromise = key as IValuePromise;
var keyValue = nestedObjectDeserializer(reader, typeof(object));
var valuePromise = keyValue as IValuePromise;
if (keyPromise == null)
{
if (valuePromise == null)
{
// Happy path: both key and value are known
dictionary.Add(key, keyValue);
}
else
{
// Key is known, value is pending
valuePromise.ValueAvailable += v => dictionary.Add(key, v);
}
}
else
{
if (valuePromise == null)
{
// Key is pending, value is known
keyPromise.ValueAvailable += v => dictionary.Add(v, keyValue);
}
else
{
// Both key and value are pending. We need to wait until both of them becom available.
var hasFirstPart = false;
keyPromise.ValueAvailable += v =>
{
if (hasFirstPart)
{
dictionary.Add(v, keyValue);
}
else
{
key = v;
hasFirstPart = true;
}
};
valuePromise.ValueAvailable += v =>
{
if (hasFirstPart)
{
dictionary.Add(key, v);
}
else
{
keyValue = v;
hasFirstPart = true;
}
};
}
}
}
value = dictionary;
reader.Expect<MappingEnd>();
return true;
}