diff options
author | Jon Skeet <skeet@pobox.com> | 2008-08-14 20:35:20 +0100 |
---|---|---|
committer | Jon Skeet <skeet@pobox.com> | 2008-08-14 20:35:20 +0100 |
commit | b84310e1101af3c442e102f4c9ed03f3eff105fb (patch) | |
tree | 5f83c80efb0b5065610b643995fad5572731cc9b /csharp/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs | |
parent | 023d7398d6227e9613afcfe12d3d47454b0a9de5 (diff) | |
download | protobuf-b84310e1101af3c442e102f4c9ed03f3eff105fb.tar.gz protobuf-b84310e1101af3c442e102f4c9ed03f3eff105fb.tar.bz2 protobuf-b84310e1101af3c442e102f4c9ed03f3eff105fb.zip |
Field accessor implementations complete (hopefully)
Diffstat (limited to 'csharp/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs')
-rw-r--r-- | csharp/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/csharp/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs b/csharp/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs new file mode 100644 index 00000000..c9647b07 --- /dev/null +++ b/csharp/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs @@ -0,0 +1,52 @@ +using System; +using System.Reflection; +using Google.ProtocolBuffers.Descriptors; + +namespace Google.ProtocolBuffers.FieldAccess { + /// <summary> + /// Accessor for fields representing a non-repeated message value. + /// </summary> + internal sealed class SingleMessageAccessor : SinglePrimitiveAccessor { + + /// <summary> + /// The static method to create a builder for the property type. For example, + /// in a message type "Foo", a field called "bar" might be of type "Baz". This + /// method is Baz.CreateBuilder. + /// </summary> + private readonly MethodInfo createBuilderMethod; + + + internal SingleMessageAccessor(string name, Type messageType, Type builderType) + : base(name, messageType, builderType) { + + createBuilderMethod = ClrType.GetMethod("CreateBuilder", BindingFlags.Public | BindingFlags.Static); + if (createBuilderMethod == null) { + throw new ArgumentException("No public static CreateBuilder method declared in " + ClrType.Name); + } + } + + /// <summary> + /// Creates a message of the appropriate CLR type from the given value, + /// which may already be of the right type or may be a dynamic message. + /// </summary> + private object CoerceType(object value) { + + // If it's already of the right type, we're done + if (ClrType.IsInstanceOfType(value)) { + return value; + } + + // No... so let's create a builder of the right type, and merge the value in. + IMessage message = (IMessage) value; + return CreateBuilder().MergeFrom(message).Build(); + } + + public override void SetValue(IBuilder builder, object value) { + base.SetValue(builder, CoerceType(value)); + } + + public override IBuilder CreateBuilder() { + return (IBuilder) createBuilderMethod.Invoke(null, null); + } + } +}
\ No newline at end of file |