在派生泛型实例上调用静态扩展方法



我有一个空的IContext

public interface IContext {
}

我还有两个派生接口IBasicContextITypedContext

public interface IBasicContext : IContext {
string Id { get; }
}
public interface ITypedContext<T> : IContext {
T Value { get; }
}

我还有另一个项目,其中包含一些处理这些上下文的代码:

internal static ProcessedContext Process(this IContext context) {
if (context is IBasicContext basicContext) {
return basicContext.Process();
} else if (context.GetType().IsAssignableFrom(typeof(ITypedContext<>))){
// What do I do here??
}
}
internal static ProcessedContext Process(this IBasicContext context) {
// Do stuff here to create processed context
}
internal static ProcessedContext Process<T>(this ITypedContext<T> context) {
// Do stuff here to create processed context
}

注1:我已经检查了多个帖子。他们中的大多数人都询问有关强制转换为基本泛型类的问题,这不是我在这里要做的。

注意 2:上下文类位于自己的项目中。它们只是数据结构,ProcessedContext创建代码不属于上下文项目。

注3:T可以是我仅在运行时创建的多种类型之一。每种类型都有多个案例是令人生畏和丑陋的。ITypedContext的处理并不真正关心T.它调用另一个泛型方法。

这会有帮助吗?

这会在运行时创建通用ProcessGeneric<T>方法的合适版本,并使用运行时实例ITypedContext<T>调用它。

internal static ProcessedContext Process(this IContext context)
{
if (context is IBasicContext basicContext)
{
return basicContext.Process();
}
else if (context.GetType().GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ITypedContext<>)))
{
Type typedContextInterface = context.GetType().GetInterfaces().First(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ITypedContext<>));
MethodInfo processGenericMethod = GetType().GetTypeInfo().GetMethod(nameof(ProcessGeneric), BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(typedContextInterface.GetGenericArguments()[0]);
return (ProcessedContext)processGenericMethod.Invoke(null, new object[] { context });
}
}
internal static ProcessedContext ProcessGeneric<T>(ITypedContext<T> context)
{
// Do stuff here to create processed context
}

最新更新