C#在方法或属性中使用sealed时的操作与原理
C#在方法或属性中使用sealed时的操作与原理
2014年12月03日 19:26:56 成成_Baby 阅读数 2126
在《C#高级编程》第100页中间部分提到”要在方法或属性上使用sealed关键字,必需先从基类上把它声明为要重写的方法或属性。如果基类上不希望有重写的方法或属性,就不要把它声明为virtual。“
这一句话有点绕口,研究了很长时间才搞懂,假设一个类MyClass中存在sealed方法MyMethod或sealed属性MyProperty,那么,存在两种可能:
(1)MyClass未显式定义基类,那么.NET默认System.Object类为MyClass类的基类,且在Object类中存在MyMethod或MyProperty,并且它们被声明为virtual,在MyClass类中,MyMethod或MyProperty声明且定义为override。若Object类中不存在MyMethod或MyProperty就会产生编译错误。
-
namespace test -
{ -
class MyClass -
{ -
public sealed override void MyMethod() -
{ -
} -
} -
class Program -
{ -
public static int Main() -
{ -
return 0; -
} -
} -
}
编译信息如下: test.cs(5,31): error CS0115: “test.MyClass.MyMethod()”:
没有找到适合的方法来重写
(2)MyClass定义基类BaseClass,则在BaseClass类中存在MyMethod或MyProperty,并且它们被声明为virtual,在MyClass类中,MyMethod或MyProperty声明且定义为override。若BaseClass类中不存在MyMethod或MyProperty就会产生编译错误。
-
using System; -
namespace Test -
{ -
class Father -
{ -
} -
class Base : Father -
{ -
public sealed override void MyProperty() { get; set; } -
} -
public class Program -
{ -
static int Main() -
{ -
return 0; -
} -
} -
}
编译信息如下: test.cs(9,31): error CS0115: “Test.MyClass.MyProperty()”:
没有找到适合的方法来重写

浙公网安备 33010602011771号