草庐IT

c# - 为什么泛型类型推断在那种情况下不起作用?

当尝试在LINQPad中编译以下代码时:voidMain(){DriveInfo.GetDrives().Select(GetProviderName).Dump();}staticstringGetProviderName(DriveInfodrive){//someirrelevantWMIcode...}我收到以下错误:Thetypeargumentsformethod'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,System.Func)'cannotbeinferredfromtheu

C#构造函数泛型参数推断

这个问题在这里已经有了答案:Whydoesn'tC#supportimpliedgenerictypesonclassconstructors?(3个答案)关闭9年前。为什么C#为方法推断泛型参数而不为构造函数推断泛型参数?newTuple(5,5)与Tuple.Create(5,5)

c# - 方法推断不适用于方法组

考虑voidMain(){varlist=new[]{"1","2","3"};list.Sum(GetValue);//errorCS0121list.Sum(s=>GetValue(s));//works!}doubleGetValue(strings){doubleval;double.TryParse(s,outval);returnval;}CS0121错误的描述是Thecallisambiguousbetweenthefollowingmethodsorproperties:'System.Linq.Enumerable.Sum(System.Collections.Gen

无法从具有多个返回的 Select 中的用法推断出 C# 类型参数

我不认为我在做任何太深奥的事情,但我没有看到任何其他关于此的问题。以下代码(我已将其简化为基本要素)在C#4中生成编译器错误。但是,类型参数是什么应该是显而易见的-最大公分母(“A类”)也是在方法“Frob”的返回类型中明确定义。编译器不应该列出lambda表达式中的所有返回类型,创建一个祖先树来找到它们的共同祖先,然后将其与包含方法的预期返回类型进行协调吗?Thetypeargumentsformethod'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,System.Func)'cannotb

c# - Fluent API 的类型推断

我有以下扩展方法:publicstaticIFooFoo(thisIFluentApiapi,Actionaction);publicstaticIFooFoo(thisIFluentApiapi,Funcfunc);publicstaticIBarBar(thisIFoofoo);publicstaticvoidFooBar(thisIBarbar,Actionaction);publicstaticvoidFooBar(//action);通用接口(interface)总是派生自它们对应的非通用接口(interface)。不幸的是,要完成这项工作:api.Foo(x=>Return

c# - 部分类型推断

我有一个像这样的通用方法(简化版):publicstaticTResultPartialInference(Funcaction,objectparam){returnaction((T)param);}在上面,param是object类型。这是要求的一部分。当我填写类型时,我可以这样调用:vartest1=PartialInference(p=>p.EndsWith("!"),"Helloworld!");但是,我想使用类型推断。最好,我想这样写:vartest2=PartialInference(p=>p.EndsWith("!"),"Helloworld!");但这不编译。我想到

c# - 没有通用扩展方法的类型推断

我有以下方法:publicstaticTEventInvocatorParametersUntil(thisTEventInvocatorParametersp,FuncbreakCond)whereTEventInvocatorParameters:EventInvocatorParameterswhereTEventArgs:EventArgs{p.BreakCondition=breakCond;returnp;}还有这个类publicclassEventInvocatorParameterswhereT:EventArgs{publicFuncBreakCondition{ge

c# - 为什么我必须显式提供泛型参数类型而编译器应该推断类型?

为什么我必须显式提供泛型参数类型,而编译器应该推断类型?publicstaticT2Cast(thisT1arg)whereT2:classwhereT1:class{returnargasT2;}示例用法:objOfTypeT2=objOfTypeT1.Cast();与我希望使用更智能的编译器的用法相比:objOfTypeT2=objOfTypeT1.Cast();或者也许我应该更聪明:-)请注意我提供了返回类型。我不想提供我在其上调用函数的对象,该方法是一个扩展方法。 最佳答案 推理不考虑返回类型;但是,您可以尝试拆分泛型;例如

C# 方法组类型推断

我正在尝试编写一个提供参数并调用函数的通用方法,如下所示:classMyClass{publicintMethod(floatarg)=>0;}TResultCall(Funcfunc)=>func(default(T1));voidMain(){varm=newMyClass();varr1=Call(m.Method);varr2=Call(m.Method);//CS0411}最后一行编译失败CS0411.是否有任何解决方法可以让类型推断在这里工作?用例:使用AutoFixture生成函数调用参数。 最佳答案 很遗憾,不能,这

c# - .NET:静态方法的推断泛型类型

假设我有publicstaticListMap(Listinputs,Funcf){returninputs.ConvertAll((x)=>f(x));}privateintSquare(intx){returnx*x;}publicvoidRun(){varinputs=newList(newint[]{2,4,8,16,32,64,128,256,512,1024,2048});//thisdoesnotcompilevaroutputs=Map(inputs,Square);//thisisfinevaroutputs2=Map(inputs,Square);//thisisa