编译器错误 CS0501
“member function”必须声明主体,因为它未标记为 abstract、extern 或 partial
非抽象方法必须具有实现。
说明
在 C# 中,属于类的方法/函数必须具有“主体”或实现。 编译器需要知道调用这些方法时应发生的情况,以便它知道要执行哪些操作。 编译器无法接受没有主体的方法,因为它希望避免混淆代码的意图。
此规则存在例外情况:
示例
下面的示例生成 CS0501:
public class MyClass
{
public void MethodWithNoBody(); // CS0501 declared but not defined
}
这可以通过声明主体(通过添加括号)来解决:
public class MyClass
{
public void MethodWithNoBody() { } // No error; compiler now interprets as an empty method
}
注意
使用括号定义方法主体时,请勿添加分号。 这样做将触发编译器错误 CS1597。
或者,使用适当的关键字,例如定义 abstract
方法:
abstract class MyClass // class is abstract; classes that inherit from it will have to define MyAbstractMethod
{
public abstract void MyAbstractMethod(); // Compiler now knows that this method must be defined by inheriting classes.
}
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈