Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 禁止重写派生类中的方法_C#_.net_Inheritance_Overriding - Fatal编程技术网

C# 禁止重写派生类中的方法

C# 禁止重写派生类中的方法,c#,.net,inheritance,overriding,C#,.net,Inheritance,Overriding,这是我的类,我不想在子类中重写此方法,我如何实现此行为 class A { public virtual void demo() { } } class B : A { public override void demo() { } } // when Class B be inherited in C, methods can be overridden further, // but I don't want the meth

这是我的类,我不想在子类中重写此方法,我如何实现此行为

class A 
{ 
   public virtual void demo() 
   { 
   } 
} 

class B : A 
{ 
   public override void demo() 
   { 
   } 
} 

// when Class B be inherited in C, methods can be overridden further, 
// but I don't want the method to be overridden further.
class C : B 
{ 

}
您只需要修改器:

public sealed override void demo() 
{ 
    // Whatever implementation
} 
(当然,我假设它通常是一个符合.NET约定的名称。)

如果要防止在不更改行为的情况下重写该方法,则需要重写它,但要显式调用以前的行为:

public sealed override void demo() 
{ 
    base.demo();
} 

请注意,当应用于方法(或属性)时,
sealed
只能与
override
一起应用,
override void demo()之前放置'
sealed
'修饰符。


你想用这个方法吗?
class A 
{ 
    public virtual void demo() 
    { 
    } 
} 

class B:A 
{ 
    public sealed override void demo() 
    { 
    } 
} 

//B can be inherited in C but demo() method can not be overriden further 
class C:B 
{ 

}