简体   繁体   English

实现泛型类型的通用扩展方法

[英]Implementing Generic Extension Method for Generic Type

If you're implementing generic extension method for generic class is there a better way? 如果你为泛型类实现泛型扩展方法有更好的方法吗? Because it would be natural to call func2 exactly as func1<V>() rather than func2<T, V>() ie to omit T parameter and call it like func2<V>() 因为将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 
    }
}

If func2() had only the generic parameter T , the compiler could infer it and you could call it without specifying the parameter. 如果func2()只有通用参数T ,编译器可以推断它,你可以在不指定参数的情况下调用它。

But if you need both parameters, you have to specify them explicitly. 但是如果您需要两个参数,则必须明确指定它们。 Type inference is all or nothing: either it can infer all types used (and you don't have to specify them), or it can't and you have to specify all of them. 类型推断是全部或全无:它可以推断所有使用的类型(并且您不必指定它们),或者它不能并且您必须指定所有类型。

In your example, class A does not know about V , it only knows V in the context of func1 . 在您的示例中, A类不知道V ,它只知道func1上下文中的V So func2 cannot magically infer V . 所以func2不能神奇地推断V

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM