Generic Extension with less arguments than parameters

点点圈 提交于 2019-12-12 02:54:18

问题


I stumbled with this issue, if I define a class

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

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

And declare extensions.

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
    }

}

When calling them:

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.

It exits with error.

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?)

After testing I found that the extension must use each generic parameter in a function attribute.

Why is this?

Are there any work arounds?


CONTEXT

Thanks to this answer I was able to implement constrains on generic classes (to make them behave like C++ template specialisation). The solution uses extensions constrains to produce compile time errors on non implemented specialisations.


回答1:


There's no need to use each generic parameter. Your nonWorkingExtension() must work. I'm pretty sure that the error you're getting is not related to the code you've posted.

Anyway, back to the question. You don't need to use any generic constrains in this code, just use MyClass<T, U> instead:

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
    }
}


来源:https://stackoverflow.com/questions/36022971/generic-extension-with-less-arguments-than-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!