nev*_*iev 6 c# generics extension-methods
如果你为泛型类实现泛型扩展方法有更好的方法吗?因为完全调用func2是很自然的,func1<V>()而不是func2<T, V>()省略T参数并将其称为func2<V>()
public class A<T> where T : class {
public V func1<V>() {
//func1 has access to T and V types
}
}
public static class ExtA {
// to implement func1 as extension method 2 generic parameters required
// and we need to duplicate constraint on T
public static V func2<T, V>(this A<T> instance) where T : class {
// func2 has access to V & T
}
}
Run Code Online (Sandbox Code Playgroud)
如果func2()只有泛型参数T,编译器可以推断它,并且您可以在不指定参数的情况下调用它。
但如果您需要这两个参数,则必须明确指定它们。类型推断要么全有,要么全无:要么它可以推断所有使用的类型(并且您不必指定它们),要么不能,您必须指定所有类型。