在Func中使用泛型类型参数,并使用特定类型调用Func?

san*_*kum 2 c# generics

我在以下方法中T使用了以下方法Func:

public void DoSomething<T>(string someString, Func<T, bool> someMethod) 
{    
    if(someCondition) 
    {
        string A;
        bool resultA = someMethod(A);
    }
    else 
    {
        string[] B;
        bool resultB = someMethod(B);
    }    
    // Some other stuff here ...
}
Run Code Online (Sandbox Code Playgroud)

DoSomething按以下方式调用该方法:

DoSomething<string>("abc", someMethod);
DoSomething<string[]>("abc", someMethod);
Run Code Online (Sandbox Code Playgroud)

someMethod存在以下定义:

bool someMethod(string simpleString);
bool someMethod(string[] stringArray);
Run Code Online (Sandbox Code Playgroud)

现在编译失败,方法中出现以下错误DoSomething:

cannot convert from 'string' to 'T'
cannot convert from 'string[]' to 'T'
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚是否有问题的解决方案,或者我正在尝试的是不可行的.它看起来类似于问题如何使用泛型类型参数传入func?虽然它对我的场景没有帮助.

Joh*_* Wu 5

你的例子看起来有点不一致,但如果你一般写东西,它应该看起来更像这样:

public void DoSomething<T>(string someString, Func<T, bool> someMethod) 
{
    T a;
    someMethod(a);
}
Run Code Online (Sandbox Code Playgroud)

请注意,不是使用if在类型之间进行选择,然后将类型声明为a string或者string[],而是简单地将类型声明为T,在编译代码时将替换它,以便它适合于该函数.

当您发现自己使用if或在类型之间进行选择时switch case,您可能不希望使用通用解决方案; 事实上,逻辑根本不是通用的.这是具体的.在这种情况下,只需编写两个原型:

public void DoSomething(string someString, Func<string, bool> someMethod) 
{    
    string A;
    bool resultA = someMethod(A);
}


public void DoSomething(string someString, Func<string[], bool> someMethod) 
{    
    string[] A;
    bool resultA = someMethod(A);
}
Run Code Online (Sandbox Code Playgroud)

这称为方法重载.编译器将通过从提供的函数推断类型来自动选择具有正确参数的正确方法.