参数少于参数的通用扩展

Generic Extension with less arguments than parameters

我偶然发现了这个问题,如果我定义一个 class

class MyClass<T,U> {
    internal T myEement {get;set;}

    public MyClass(T Element) {
        myEement = Element;
    }
}

并声明扩展。

static class MyClassExtension{


    //What I want to do
    public static void nonWorkingExtension<P,T,U>(this P p, U u) where P:MyClass<T,U>
    {
        T Element = p.myEement;
        //Do something with u and p.Element
    }

    //What I have to do
    public static void workingExtension<P, T, U>(this P p, T dummy, U u) where P : MyClass<T, U>
    {
        T Element = p.myEement;
        //Do something with u and p.Element
    }

}

打电话给他们时:

MyClass<int, double> oClass = new MyClass<int, double>(3);

oClass.workingExtension(0,0.3); //I can call this one.
oClass.nonWorkingExtension(0.3); //I can't call this.

错误退出。

Error 1 'MyClass' does not contain a definition for 'doSomething' and no extension method 'doSomething' accepting a first argument of type 'MyClass' could be found (are you missing a using directive or an assembly reference?)

经过测试,我发现扩展 必须 在函数属性中使用每个通用参数。

这是为什么?

有什么变通办法吗?


上下文

感谢 this answer 我能够对泛型 classes 实施约束(使它们表现得像 C++ 模板专业化)。该解决方案使用扩展约束在未实现的专业化上产生编译时错误。

没有必要使用每个通用参数。您的 nonWorkingExtension() 必须有效。我很确定您遇到的错误与您发布的代码无关。

不管怎样,回到问题。您不需要在此代码中使用任何通用约束,只需使用 MyClass<T, U> 代替:

static class MyClassExtension
{
    public static void nonWorkingExtension<T, U>(this MyClass<T, U> p, U u)
    {
        T Element = p.myEement;
        //Do something with u and p.Element
    }
}