c#如何对方法签名中的泛型Func参数设置约束

con*_*att 4 c# generics

public void Test<TFeature>(Func<TController, ViewResult> controllerAction)                                          
            where TController : IController
            where TFeature : ISecurityFeature
        {
            ...
        }
Run Code Online (Sandbox Code Playgroud)

我收到错误,Test没有定义类型参数TController.如何在TController上设置约束?

Tre*_*ley 5

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

public void Test<TFeature, TController>(Func<TController, ViewResult> controllerAction)                                          
        where TController : IController
        where TFeature : ISecurityFeature
    {
        ...
    }
Run Code Online (Sandbox Code Playgroud)


Kri*_*izz 5

除非你在里面定义它SomeClass<TController>(在这种情况下你需要将约束放在旁边class SomeClass<TController>),你需要为TController你的函数创建一个泛型参数,即:

public void Test<TFeature, TController>(Func<TController, ViewResult> controllerAction)                                          
            where TController : IController
            where TFeature : ISecurityFeature
        {
            ...
        }
Run Code Online (Sandbox Code Playgroud)