Troubleshooting: Why doesn't type inference fail here?
Given a type declared as shown below
public cla开发者_开发知识库ss EqualityProbe<T>
{
public EqualityProbe( Func<T> functionToGetActualValue, T expectedValue, string probeDescription) {..}
Client code:
// cannot infer bool here
new EqualityProbe(CanConnectToMachine, true, "Probe machine is online")
// compiles fine
new EqualityProbe<bool>(CanConnectToMachine, true, "Probe machine is online")
My understanding is that type-inference doesn't work for method groups (e.g. CanConnectToMachine) or anonymous methods (lambda expressions).
But in this case, why doesn't the compiler infer the type argument from the second argumentC# doesn't support type inference on constructors, although this can often be overcome through the use of a factory class.
See the answer here: Why can't the C# constructor infer type?
Well, that how C# is ! It doenst infer for constructors. While instantiating a generic type, you need to specify the Type(s) that will be used for the generic ones.
精彩评论