问题
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