2015-08-14 38 views
2

假设下面的界面,我使用来定义参数类型和用于存储过程返回类型...使用通用接口作为typeparameter为方法或函数

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

回答

4

您需要使用类型参数,你指定的接口:

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

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

+1

我不确定这个编译。它不应该是'DoAction '? –

+1

@Charles:对不起,是的。重点是参数,并没有发现类型参数问题。固定。 –

+0

是的,现在的作品谢谢你,并回答alsow什么是我的下一个问题是如何使该方法成为一个函数返回一个TReturnType的列表,但现在所有的作品现在这样.. public list 的getAction (IStoredProcedure 程序1) 其中TReturnType:类 其中TParameterType:类 {// 做一些工作 返回新的List (); } – Dib

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

这并没有为我编译。 – Dib

+1

编辑完成后立即编译,但@Jon Skeet首先使用了符合我的需求的编译解决方案,因此接受了他的答案。抱歉。 – Dib

+1

另外,对于非泛型的东西使用类型参数会造成混淆和不必要。在某些情况下,使用'TProcedure'会很有用(例如,如果您返回了“TProcedure”),但这不是其中之一。 – Luaan