c#如何对方法签名中的泛型Func参数设置约束 公共无效测试(Func controllerAction) 其中t控制器:i控制器 其中t功能:ISecurityFeature { ... }

c#如何对方法签名中的泛型Func参数设置约束 公共无效测试(Func controllerAction) 其中t控制器:i控制器 其中t功能:ISecurityFeature { ... },c#,generics,C#,Generics,我得到一个错误,测试没有定义类型参数TController。如何对TController设置约束?您还需要将TController添加为通用参数 public void Test<TFeature>(Func<TController, ViewResult> controllerAction) where TController : IController

我得到一个错误,测试没有定义类型参数TController。如何对TController设置约束?

您还需要将TController添加为通用参数

public void Test<TFeature>(Func<TController, ViewResult> controllerAction)                                          
            where TController : IController
            where TFeature : ISecurityFeature
        {
            ...
        }
公共无效测试(Func controllerAction)
其中t控制器:i控制器
其中t功能:ISecurityFeature
{
...
}

除非您在
SomeClass
中定义它(在这种情况下,您需要在
class SomeClass
旁边放置约束),否则您需要将
TController
作为函数的通用参数,即:

public void Test<TFeature, TController>(Func<TController, ViewResult> controllerAction)                                          
        where TController : IController
        where TFeature : ISecurityFeature
    {
        ...
    }
公共无效测试(Func controllerAction)
其中t控制器:i控制器
其中t功能:ISecurityFeature
{
...
}

看起来我们几乎同时回答了这个问题,值得一提的是类可以定义TController类型。
public void Test<TFeature, TController>(Func<TController, ViewResult> controllerAction)                                          
            where TController : IController
            where TFeature : ISecurityFeature
        {
            ...
        }