C#基类/接口,带有接受派生类作为参数的泛型方法

时间:2017-06-07 14:19:33

标签: c# generics inheritance derived-class

我想在基类(和接口)中定义一个接受派生类作为其参数的方法。

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

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

如果有人能告诉我界面会是什么样子以及如何做到这一点我会永远感激......或者如果可能的话

预期

兰斯

2 个答案:

答案 0 :(得分:4)

你可能正在寻找:

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

    }
}

谢谢@Phil

答案 1 :(得分:0)

您可以使用泛型类,其泛型类型必须是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 ....
    }
}