public void ReflectionGetOneof() { TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); reflectionTester.SetAllFieldsViaReflection(builder); Descriptors.OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0]; Descriptors.FieldDescriptor field = TestAllTypes.Descriptor.FindFieldByName("oneof_bytes"); Assert.AreSame(field, builder.OneofFieldDescriptor(oneof)); }
/// <summary> /// Verifies that the given object is of the correct type to be a valid /// value for the given field. /// </summary> /// <remarks> /// For repeated fields, this checks if the object is of the right /// element type, not whether it's a list. /// </remarks> /// <exception cref="ArgumentException">The value is not of the right type.</exception> /// <exception cref="ArgumentNullException">The value is null.</exception> private static void VerifyType(IFieldDescriptorLite field, object value) { ThrowHelper.ThrowIfNull(value, "value"); bool isValid = false; switch (field.MappedType) { case MappedType.Int32: isValid = value is int; break; case MappedType.Int64: isValid = value is long; break; case MappedType.UInt32: isValid = value is uint; break; case MappedType.UInt64: isValid = value is ulong; break; case MappedType.Single: isValid = value is float; break; case MappedType.Double: isValid = value is double; break; case MappedType.Boolean: isValid = value is bool; break; case MappedType.String: isValid = value is string; break; case MappedType.ByteString: isValid = value is ByteString; break; case MappedType.Enum: IEnumLite enumValue = value as IEnumLite; isValid = enumValue != null && field.EnumType.IsValidValue(enumValue); break; case MappedType.Message: IMessageLite messageValue = value as IMessageLite; isValid = messageValue != null; #if !LITE if (isValid && messageValue is IMessage && field is FieldDescriptor) { isValid = ((IMessage)messageValue).DescriptorForType == ((FieldDescriptor)field).MessageType; } #endif break; } if (!isValid) { // When chaining calls to SetField(), it can be hard to tell from // the stack trace which exact call failed, since the whole chain is // considered one line of code. So, let's make sure to include the // field name and other useful info in the exception. string message = "Wrong object type used with protocol message reflection."; #if !LITE Google.ProtocolBuffers.Descriptors.FieldDescriptor fieldinfo = field as Google.ProtocolBuffers.Descriptors.FieldDescriptor; if (fieldinfo != null) { message += "Message type \"" + fieldinfo.ContainingType.FullName; message += "\", field \"" + (fieldinfo.IsExtension ? fieldinfo.FullName : fieldinfo.Name); message += "\", value was type \"" + value.GetType().Name + "\"."; } #endif throw new ArgumentException(message); } }