简体   繁体   中英

implementing generic interfaces in c#

how can we inherit generic interfaces in to a generic class? I have tried below code and getting error message: "Bc' does not implement interface member 'ConsoleApplication3.iB.showval(int, int)". How it could be solved?

interface iB<X, Y> 
{
    void storeval(X p1,Y p2);
    void getval();
}
class Bc<X,Y>:iB<int,int>
{
    private X _dm1;
    private Y _dm2;
    public void storeval(X p1,Y p2) 
    {
        this._dm1 = p1;
        this._dm2 = p2;
    }
    public void getval() 
    {
        Console.WriteLine("{0}\t{1}",this._dm1,this._dm2);
    }
}
class Program
{
    static void Main(string[] args)
    {
        Bc<string, bool> b1 = new Bc<string, bool>();
        b1.storeval("AppScienti",true);
        b1.getval();
        Console.ReadKey();
    }
}

Your code is not inheriting a generic interface - it inherits a fully defined instance of a generic interface.

Since you inherit iB<int,int> , you need to implement

public void storeval(int p1, int p2) {
    ...
}

Alternatively, you could inherit iB<X,Y> , in which case your implementation of the interface would have worked:

class Bc<X,Y> : iB<X,Y> {
    ...
}

In either case, the parameters of the interface methods dependent on type parameters of the generic interface need to match the type parameters that you specify when inheriting the interface.

With class Bc<X, Y> : iB<int, int> you define a new generic class, with two new generic type parameters, that happens to implement iB<int, int> . It's more clear if you rename them: class Bc<NewX, NewY> : iB<int, int> .

Your two new generic type parameters have nothing to do with the parameters defined by the interface. You can now declare a new Bc<string, bool> variable while the class still implements iB<int, int> .

You'll have to alter your method signature to let it implement iB<int, int>.storeval(int, int) :

public void storeval(int p1, int p2) 

If you change your Bc class to inherit the generic parameters like this:

class Bc<X, Y> : iB<X, Y>

You can instantiate one like this:

var bcInt = new Bc<int, int>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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