简体   繁体   中英

C# base class/Interface with a generic method that accepts the derived class as a parameter

I would like to have a method defined on the base class (and in an interface) that accepts a derived class as its parameter.

ie

abstract class Base : IBase
{
    public void CloneMeToProvidedEntity(??? destination) {};
}

public class Derived : Base
{
     public override void CloneMeToProvidedEntity(Derived destination)
     {
         blah blah ....
     }
}  

I would be eternally grateful if someone can tell me what the Interface would look like and how to do this... or if possible

With Anticipation

Lance

You're probably looking for:

interface IBase<T>
{
    void CloneMeToProvidedEntity(T destination);
}

public abstract class Base<T> : IBase<T>
{
    public virtual void CloneMeToProvidedEntity(T destination) { }
}

public class Derived : Base<Derived>
{
    public override void CloneMeToProvidedEntity(Derived destination)
    {

    }
}

Thanks @Phil

You can use a generic class where the generic type have to be of type IBase :

public abstract class Base<T> : IBase where T : IBase
{
    public virtual void CloneMeToProvidedEntity(T destination) { }
}

public class Derived : Base<Derived>
{
    public override void CloneMeToProvidedEntity(Derived destination)
    {
        // blah blah ....
    }
}

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