Browse Source

Add method for Any.Is (#5207)

Sydney Acksman 7 years ago
parent
commit
3f826a6dbf

+ 13 - 0
csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs

@@ -140,5 +140,18 @@ namespace Google.Protobuf.WellKnownTypes
             var message = new TestWellKnownTypes { AnyField = new Any() };
             Assert.AreEqual("{ \"anyField\": { \"@type\": \"\", \"@value\": \"\" } }", message.ToString());
         }
+
+        [Test]
+        public void IsWrongType()
+        {
+            var any = Any.Pack(SampleMessages.CreateFullTestAllTypes());
+            Assert.False(any.Is(TestOneof.Descriptor));
+        }
+
+        public void IsRightType()
+        {
+            var any = Any.Pack(SampleMessages.CreateFullTestAllTypes());
+            Assert.True(any.Is(TestAllTypes.Descriptor));
+        }
     }
 }

+ 11 - 0
csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs

@@ -67,6 +67,17 @@ namespace Google.Protobuf.WellKnownTypes
             return lastSlash == -1 ? "" : typeUrl.Substring(lastSlash + 1);
         }
 
+        /// <summary>
+        /// Returns a bool indictating whether this Any message is of the target message type
+        /// </summary>
+        /// <param name="descriptor">The descriptor of the message type</param>
+        /// <returns><c>true</c> if the type name matches the descriptor's full name or <c>false</c> otherwise</returns>
+        public bool Is(MessageDescriptor descriptor)
+        {
+            ProtoPreconditions.CheckNotNull(descriptor, nameof(descriptor));
+            return GetTypeName(TypeUrl) == descriptor.FullName;
+        }
+
         /// <summary>
         /// Unpacks the content of this Any message into the target message type,
         /// which must match the type URL within this Any message.