add python equiv in core

This commit is contained in:
Jack Gerrits
2025-01-27 11:59:57 -05:00
committed by Jack Gerrits
parent 51b992cfd5
commit 0497592e8a
2 changed files with 68 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// IHandle.cs
using Google.Protobuf;
namespace Microsoft.AutoGen.Core.Python;
/// <summary>
/// Defines a handler interface for processing items of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type of item to be handled, which must implement <see cref="IMessage"/>.</typeparam>
public interface IHandle<in T> where T : IMessage
{
/// <summary>
/// Handles the specified item asynchronously.
/// </summary>
/// <param name="item">The item to be handled.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task Handle(T item, CancellationToken cancellationToken = default);
}
public interface IHandle<in InT, OutT> where InT : IMessage where OutT : IMessage
{
/// <summary>
/// Handles the specified item asynchronously.
/// </summary>
/// <param name="item">The item to be handled.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task<OutT> Handle(InT item, CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,38 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// IHandleExtensions.cs
using System.Reflection;
namespace Microsoft.AutoGen.Core.Python;
/// <summary>
/// Provides extension methods for types implementing the IHandle interface.
/// </summary>
public static class IHandleExtensions
{
/// <summary>
/// Gets all the handler methods from the interfaces implemented by the specified type.
/// </summary>
/// <param name="type">The type to get the handler methods from.</param>
/// <returns>An array of MethodInfo objects representing the handler methods.</returns>
public static MethodInfo[] GetHandlers(this Type type)
{
var handlers = type.GetInterfaces().Where(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IHandle<>) || i.GetGenericTypeDefinition() == typeof(IHandle<,>)));
return handlers.SelectMany(h => h.GetMethods().Where(m => m.Name == "Handle")).ToArray();
}
/// <summary>
/// Gets a lookup table of handler methods from the interfaces implemented by the specified type.
/// </summary>
/// <param name="type">The type to get the handler methods from.</param>
/// <returns>A dictionary where the key is the generic type and the value is the MethodInfo of the handler method.</returns>
public static Dictionary<Type, MethodInfo> GetHandlersLookupTable(this Type type)
{
var handlers = type.GetHandlers();
return handlers.ToDictionary(h =>
{
var generic = h.DeclaringType!.GetGenericArguments();
return generic[0];
});
}
}