本文介绍了泛型扩展,参数少于参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

并声明扩展名.

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.

错误退出.

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

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

这是为什么?

有什么解决方法吗?

上下文

感谢这个答案我能够对泛型类实施约束(使它们的行为类似于C ++模板专业化) .该解决方案使用扩展约束来在未实施的专业上产生编译时错误.

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.

推荐答案

无需使用每个通用参数.您的nonWorkingExtension()必须正常工作.我很确定您收到的错误与您发布的代码无关.

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.

无论如何,回到问题所在.您无需在此代码中使用任何常规约束,只需使用MyClass<T, U>即可:

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

这篇关于泛型扩展,参数少于参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 04:33