强制将抽象的实施方式赋予子代的子代

问题描述 投票:0回答:6

我想要这样的东西

    public abstract class abc
    {
        public abstract void test();
    }

    public class def : abc
    {
            // ignore test(), this is concrete class which can be initialized
            // test method is not needed for this class
    }

    public class ghi : def
    {
        public override void test()
        {
            // force test method implementation here
        }
    }

有什么办法可以做到这一点。我想忽略GHI类的接口使用,因为这些不在我们的应用范围内。

编辑

你们都是对的,但我需要类似的实现。重点是我有各种对象,它们有共同的功能,所以我继承了一个类。我想把这个类给其他必须实现测试方法的人。

c# inheritance abstract-class
6个回答
0
投票

你可以在你的基类中把Test方法作为Virtual,而把方法主体留空。因此你可以在任何你想覆盖的地方覆盖它。这更多的是一种黑客行为,使用接口是一种更好的方式。

public abstract class abc
{
    public virtual void test()
    {
    }
}

public class def : abc
{
        // ignore test(), this is concrete class which can be initialized
        // test method is not needed for this class
}

public class ghi : def
{
    public override void test()
    {
        // force test method implementation here
    }
}

或者

你可以有另一个抽象类

public abstract class abc
{
}

public abstract class lmn : abc
{
 public abstract void Test();
}
public class def : abc
{
    // ignore test(), this is concrete class which can be initialized
    // test method is not needed for this class
}

public class ghi : lmn
{
 public override void test()
 {
    // force test method implementation here
 }

} - 这个抽象完全取决于你的领域。这个建议只是一种技术上的方式。不知道其是否与当前的问题域一致。


2
投票

这是不可能的。def 必须要实现 test,除非它也是抽象的。


1
投票

编辑为粗体。抽象的意思是你必须在你的子类中实现它,如果你想强制实现不是每个 "继承者 "都有的功能,你应该使用接口。如果你想强制实现一个不是每个 "继承者 "都有的功能,你应该使用接口。这是我要做的。

public abstract class abc
{
    // Everything you want here, but not "Test()".
}

public class def : abc
{
}

public class ghi : def, ITestable
{
    public void ITestable.Test()
    {
    }
}

public interface ITestable
{
    void Test();
}

0
投票

你所做的是不可能的。你不能在基类(abc)中添加一个抽象方法,而这个方法不需要在继承基类的类(def)中实现,否则它也必须是抽象的。


0
投票

没有办法。这是个定义问题,你说 "我希望每个继承自这个类的类都有这个方法",然后试图创建一个没有这个方法的子类。


0
投票

你需要把def class做成抽象类。

© www.soinside.com 2019 - 2024. All rights reserved.