我有这样的通用方法(简化版):
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) 为什么我必须提供显式泛型参数类型而编译器应该推断出类型?
public static T2 Cast<T1,T2>(this T1 arg) where T2 : class where T1 : class
{
return arg as T2;
}
Run Code Online (Sandbox Code Playgroud)
样品用法:
objOfTypeT2 = objOfTypeT1.Cast<TypeT1,TypeT2>();
Run Code Online (Sandbox Code Playgroud)
与我对更智能的编译器的期望用法相比:
objOfTypeT2 = objOfTypeT1.Cast<TypeT2>();
Run Code Online (Sandbox Code Playgroud)
或者我应该更聪明:-)
请注意,我提供了返回类型.我想不提供我在其上调用函数的对象,该方法是一个扩展方法.
我希望编译器为我推断出一种类型,但我不确定它是否可行,或者最好的选择是什么.
我想这样做:
public static TValue Get<TValue>(TKey key) where TValue : Mapped<TKey> { ... }
public class MyObject : Mapped<int> { ... }
Run Code Online (Sandbox Code Playgroud)
而C#推断TKey是一个int.有没有办法做这样的事情?如果没有,最好的选择是什么?
我想避免做类似的事情 Get<MyObject, int>(1);
编辑: