コードインスペクション: 冗長な「abstract」修飾子
C# 8.0 以降、インターフェースのメンバーで abstract 修飾子を使用できます。 ただし、この修飾子はオプションです。インターフェースのメンバーはデフォルトで抽象化されているため、実装クラスで必ずオーバーライドする必要があります。ただし、 デフォルト実装 を持つ場合(これも C# 8.0 の新機能)を除きます。
そのため、ほとんどの場合 abstract 修飾子は冗長なものです。本文のないインターフェースメンバーは同様のバイトコードにコンパイルされます。 インターフェースメンバーで abstract 修飾子を使用する必要がある唯一のケースは、このメンバーが基底インターフェースのデフォルト実装を打ち消す場合です:
interface IBase
{
public void Foo() { Console.WriteLine("default implementation"); }
}
class DerivedFromBase : IBase
{
// no need to override 'Foo' since it has a default implementation
}
interface IAbstract : IBase
{
// Implementation without a body cancels the default implementation
// in the base interface and has to be 'abstract'
abstract void IBase.Foo();
// 'abstract' is redundant because this member is abstract anyway
abstract void Bar();
}
class DerivedFromAbstract : IAbstract
{
// Default implementation of 'Foo()' is cancelled
// with 'abstract void IBase.M' in 'IAbstract'
// therefore we have to provide an implementation here and
// cannot use the default implementation from 'IBase'
public void Foo() { Console.WriteLine("some implementation"); }
// 'Bar' doesn't have a body in the base interface,
// therefore we have to provide an implementation anyway
public void Bar() { Console.WriteLine("some implementation"); }
}
2026 年 6 月 12 日