简体   繁体   English

抽象类中无体抽象方法有什么问题?

[英]What's wrong with bodyless abstract methods in abstract class?

I'm refactoring a pre-existing solution. 我正在重构一个已有的解决方案。 I use ReSharper and I've noticed a code inspection rule is being tripped. 我使用ReSharper并且我注意到代码检查规则正在被触发。 There is an abstract class which has bodyless method signatures with the intention of forcing the derived classes (of which there are several). 有一个抽象类,它具有无体方法签名,目的是强制派生类(其中有几个)。 As far as my knowledge goes, this is the (or at least a) correct way to do things. 据我所知,这是(或至少是)正确的做事方式。 However, ReSharper is complaining that the "Type member is never accessed via base type" and that "Only overrides of [the methods] are used." 但是,ReSharper抱怨“永远不会通过基类型访问类型成员”,并且“仅使用了[方法]的覆盖”。 Here is example code that replicates the issue in question: 以下是复制问题的示例代码:

public abstract class MyAbstractClass
{
    public abstract void CreateSomething();
    public abstract void ReadSomething();
    public abstract void InsertSomething();
}

public class MyDerivedClass : MyAbstractClass
{

    public override void CreateSomething()
    {
        throw new NotImplementedException();
    }

    public override void ReadSomething()
    {
        throw new NotImplementedException();
    }

    public override void InsertSomething()
    {
        throw new NotImplementedException();
    }
}

By the way, there are other members that rule out making the abstract class an interface. 顺便说一句,还有其他成员排除了使抽象类成为一个接口。 ReSharper suggests making changes to the 3 methods in the abstract class. ReSharper建议对抽象类中的3个方法进行更改。 Its suggestions are to make them protected, virtual, non-abstract or to simply remove them from the abstract class and only have them in derived classes. 它的建议是使它们受保护,虚拟,非抽象或简单地从抽象类中删除它们,并且只在派生类中使用它们。 Whoever originally wrote this code intended for every derived class to implement these methods, and for those methods to be public in the derived classes. 最初为每个派生类编写此代码以实现这些方法的人,以及那些在派生类中公开的方法。 So, is there some way I should change this to make it more effective? 那么,有什么方法可以改变它以使其更有效? If not, why is ReSharper taking issue with this? 如果没有,为什么ReSharper对此有疑问?

因为你永远不会使用MyAbstractClass类型的引用来访问该方法,所以将它作为一个抽象成员是没有意义的 - 你可以完全将它从基类中删除,并且所有内容都可以正常编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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