Add method for Any.Is (#5207)

This commit is contained in:
Sydney Acksman 2018-10-05 13:06:58 -05:00 committed by Jie Luo
parent 2b0a18b270
commit 3f826a6dbf
2 changed files with 24 additions and 0 deletions

View File

@ -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));
}
}
}

View File

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