/// <summary> /// Retrieves a message value for the specified option field. /// </summary> /// <param name="field">The field to fetch the value for.</param> /// <param name="value">The output variable to populate.</param> /// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns> public bool TryGetMessage <T>(int field, out T value) where T : class, IMessage, new() { if (values == null) { value = default(T); return(false); } IExtensionValue extensionValue; if (values.TryGetValue(field, out extensionValue)) { if (extensionValue is ExtensionValue <T> ) { ExtensionValue <T> single = extensionValue as ExtensionValue <T>; ByteString bytes = single.GetValue().ToByteString(); value = new T(); value.MergeFrom(bytes); return(true); } else if (extensionValue is RepeatedExtensionValue <T> ) { RepeatedExtensionValue <T> repeated = extensionValue as RepeatedExtensionValue <T>; value = repeated.GetValue() .Select(v => v.ToByteString()) .Aggregate(new T(), (t, b) => { t.MergeFrom(b); return(t); }); return(true); } } value = null; return(false); }
private bool TryGetPrimitiveValue <T>(int field, out T value) { if (values == null) { value = default(T); return(false); } IExtensionValue extensionValue; if (values.TryGetValue(field, out extensionValue)) { if (extensionValue is ExtensionValue <T> ) { ExtensionValue <T> single = extensionValue as ExtensionValue <T>; value = single.GetValue(); return(true); } else if (extensionValue is RepeatedExtensionValue <T> ) { RepeatedExtensionValue <T> repeated = extensionValue as RepeatedExtensionValue <T>; if (repeated.GetValue().Count != 0) { RepeatedField <T> repeatedField = repeated.GetValue(); value = repeatedField[repeatedField.Count - 1]; return(true); } } else // and here we find explicit enum handling since T : Enum ! x is ExtensionValue<Enum> { var type = extensionValue.GetType(); if (type.GetGenericTypeDefinition() == typeof(ExtensionValue <>)) { var typeInfo = type.GetTypeInfo(); var typeArgs = typeInfo.GenericTypeArguments; if (typeArgs.Length == 1 && typeArgs[0].GetTypeInfo().IsEnum) { value = (T)typeInfo.GetDeclaredMethod(nameof(ExtensionValue <T> .GetValue)).Invoke(extensionValue, EmptyParameters); return(true); } } else if (type.GetGenericTypeDefinition() == typeof(RepeatedExtensionValue <>)) { var typeInfo = type.GetTypeInfo(); var typeArgs = typeInfo.GenericTypeArguments; if (typeArgs.Length == 1 && typeArgs[0].GetTypeInfo().IsEnum) { var values = (IList)typeInfo.GetDeclaredMethod(nameof(RepeatedExtensionValue <T> .GetValue)).Invoke(extensionValue, EmptyParameters); if (values.Count != 0) { value = (T)values[values.Count - 1]; return(true); } } } } } value = default(T); return(false); }