2

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

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()方法中,我需要询问参数的类型和返回类型。

4

2 回答 2

4

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

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

...否则您指的是非通用IStoredProcedure接口。(不要忘记 C# 允许类型被泛型“重载”。)

于 2015-08-14T06:24:03.140 回答
1
public static void DoAction<TProcedure, TReturnType, TParameterType>(TProcedure procedure1)
        where TProcedure : IStoredProcedure<TReturnType, TParameterType>
        where TReturnType : class
        where TParameterType : class
        {
            // do some work
        }
于 2015-08-14T06:26:00.203 回答