Add method for Any.Is (#5207)

pull/5222/merge
Sydney Acksman 6 years ago committed by Jie Luo
parent 2b0a18b270
commit 3f826a6dbf
  1. 13
      csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs
  2. 11
      csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.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));
}
}
}

@ -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.

Loading…
Cancel
Save