必须声明一个正文,因为它没有标记为抽象的外部或部分

时间:2016-03-17 11:02:39

标签: c#

我有代码并得到上面显示的错误。但是Class被定义为抽象的,所以我不需要代码体。

public abstract class Endian
    {
        public short ToInt16(byte[] value, int startIndex)
        {
            return unchecked((short)FromBytes(value, startIndex, 2));
        }

        public int ToInt32(byte[] value, int startIndex)
        {
            return unchecked((int)FromBytes(value, startIndex, 4));
        }

        public long ToInt64(byte[] value, int startIndex)
        {
            return FromBytes(value, startIndex, 8);
        }

        // This same method can be used by int16, int32 and int64.
        protected virtual long FromBytes(byte[] buffer, int startIndex, int len); // << Error here
    }

3 个答案:

答案 0 :(得分:4)

virtual修饰符用于指示方法可以在派生类中被覆盖,但需要在基类中定义(即通过给它一个方法体)。您希望使用abstract修饰符而不是virtual,如错误消息所示,这意味着必须才能被覆盖。

抽象方法必须具有abstract修饰符,即使该类已标记为abstract以便明确区分它们,并且它们也不能包含方法体(最后只有分号) 。它只是规则,它就是它。

答案 1 :(得分:0)

要抽象,必须将方法声明为:

protected abstract long FromBytes(byte[] buffer, int startIndex, int len);

你声明它是虚拟的,这意味着它是一个适当的方法,有一个实现,可以被派生类覆盖。

答案 2 :(得分:0)

  

但是Class被定义为抽象,所以我不需要代码体。

为什么你会这么想?

protected virtual long FromBytes(byte[] buffer, int startIndex, int len);

方法仍然标记为虚拟,它需要一个正文并且可以覆盖。如果您不想添加定义,则应将其声明为抽象。