فهرست منبع

Fix clearing wrapper type fields with reflection.

The nullable value type fields already worked, but the use of the CLR property concealed the difference between string and StringWrapper fields.
Jon Skeet 10 سال پیش
والد
کامیت
f5a0a7feeb

+ 10 - 0
csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs

@@ -345,5 +345,15 @@ namespace Google.Protobuf.WellKnownTypes
             var message = TestWellKnownTypes.Parser.ParseFrom(stream);
             Assert.AreEqual(6, message.Int32Field);
         }
+
+        [Test]
+        public void ClearWithReflection()
+        {
+            // String and Bytes are the tricky ones here, as the CLR type of the property
+            // is the same between the wrapper and non-wrapper types.
+            var message = new TestWellKnownTypes { StringField = "foo" };
+            TestWellKnownTypes.Descriptor.Fields[TestWellKnownTypes.StringFieldFieldNumber].Accessor.Clear(message);
+            Assert.IsNull(message.StringField);
+        }
     }
 }

+ 1 - 1
csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs

@@ -197,7 +197,7 @@ namespace Google.Protobuf.Reflection
         }
 
         /// <summary>
-        /// Returns  the type of the field.
+        /// Returns the type of the field.
         /// </summary>
         public FieldType FieldType
         {

+ 1 - 1
csharp/src/Google.Protobuf/Reflection/SingleFieldAccessor.cs

@@ -61,7 +61,7 @@ namespace Google.Protobuf.Reflection
             
             // TODO: Validate that this is a reasonable single field? (Should be a value type, a message type, or string/ByteString.)
             object defaultValue =
-                typeof(IMessage).IsAssignableFrom(clrType) ? null
+                descriptor.FieldType == FieldType.Message ? null
                 : clrType == typeof(string) ? ""
                 : clrType == typeof(ByteString) ? ByteString.Empty
                 : Activator.CreateInstance(clrType);