RpcUtil.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Google.ProtocolBuffers {
  5. public static class RpcUtil {
  6. /// <summary>
  7. /// Converts an Action[IMessage] to an Action[T].
  8. /// </summary>
  9. public static Action<T> SpecializeCallback<T>(Action<IMessage> action)
  10. where T : IMessage<T> {
  11. return message => action(message);
  12. }
  13. /// <summary>
  14. /// Converts an Action[T] to an Action[IMessage].
  15. /// The generalized action will accept any message object which has
  16. /// the same descriptor, and will convert it to the correct class
  17. /// before calling the original action. However, if the generalized
  18. /// callback is given a message with a different descriptor, an
  19. /// exception will be thrown.
  20. /// </summary>
  21. public static Action<IMessage> GeneralizeCallback<T>(Action<T> action, T defaultInstance)
  22. where T : class, IMessage<T> {
  23. return message => {
  24. T castMessage = message as T;
  25. if (castMessage == null) {
  26. castMessage = (T) defaultInstance.CreateBuilderForType().MergeFrom(message).Build();
  27. }
  28. action(castMessage);
  29. };
  30. }
  31. }
  32. }