我有这样的通用方法(简化版):
public static TResult PartialInference<T, TResult>(Func<T, TResult> action, object param)
{
return action((T)param);
}
Run Code Online (Sandbox Code Playgroud)
在上面,param是object故意的类型.这是要求的一部分.
当我填写类型时,我可以这样称呼它:
var test1 = PartialInference<string, bool>(
p => p.EndsWith("!"), "Hello world!"
);
Run Code Online (Sandbox Code Playgroud)
但是,我想使用类型推断.最好,我想写这个:
var test2 = PartialInference<string>(
p => p.EndsWith("!"), "Hello world!"
);
Run Code Online (Sandbox Code Playgroud)
但这不编译.我想出的最好的是:
var test3 = PartialInference(
(string p) => p.EndsWith("!"), "Hello world!"
);
Run Code Online (Sandbox Code Playgroud)
我希望将此作为类型参数并且仍具有正确类型的返回类型的原因是因为我的实际调用看起来像这样:
var list1 = ComponentProvider.Perform(
(ITruckSchedule_StaffRepository p) => p.GetAllForTruckSchedule(this)
)
Run Code Online (Sandbox Code Playgroud)
哪个非常难看,我很乐意写这样的东西:
var list2 = ComponentProvider.Perform<ITruckSchedule_StaffRepository>(
p => p.GetAllForTruckSchedule(this)
)
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 18
您可以将t拆分为泛型类型的泛型方法:
class Foo<TOuter> {
public static void Bar<TInner>(TInner arg) {...}
}
...
int x = 1;
Foo<string>.Bar(x);
Run Code Online (Sandbox Code Playgroud)
这里推断出int,但字符串是显式的.