使用通用接口作为方法或函数的类型参数

Using generic interface as typeparameter for a method or function

假设我使用以下接口定义存储过程的参数类型和 return 类型...

public interface IStoredProcedure<out TReturn, out TParameter>
    where TReturn : class 
    where TParameter : class
{
    TReturn ReturnType { get; }

    TParameter ParameterType { get; }
}

...是否可以将此接口作为方法的 TypeParameter 传递?与此类似的东西(无法编译)

public static void DoAction<TProcedure>(TProcedure procedure1)
        where TProcedure : IStoredProcedure<TReturnType, TParameterType>
{
        // do some work
}

...或类似的内容...

public static void DoAction<IStoredProcedure<TReturnType, TParameterType>>(IStoredProcedure procedure1)
        where TReturnType : class
        where TParameterType : class
{
        // do some work
}

这两种方法都无法编译,我只是不知道如何编写它们才能编译。在 DoAction() 方法中,我需要查询参数的类型和 return 类型。

您需要在指定接口的地方使用类型参数:

public static void DoAction<TReturnType, TParameterType>
   (IStoredProcedure<TReturnType, TParameterType> procedure1)
    where TReturnType : class
    where TParameterType : class
{
    // do some work
}

...否则您指的是非通用 IStoredProcedure 接口。 (不要忘记 C# 允许类型 "overloaded" 泛型 arity。)

public static void DoAction<TProcedure, TReturnType, TParameterType>(TProcedure procedure1)
        where TProcedure : IStoredProcedure<TReturnType, TParameterType>
        where TReturnType : class
        where TParameterType : class
        {
            // do some work
        }