简体   繁体   中英

How to restrict method access one child class using inheritance in c#?

This is my code

using System;


public class parent
{
    public virtual void m1(){

    }
}
public class child1:parent{

    public sealed override void m1(){

    }
}

public class child2:parent{

    public override void m1(){    //How to stop parent method here

    }

}
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
    }
}

In the above code i have three classes. In parent class contains a virtual method that can be inherit in to child1 class only . How to restrict to inherit parent method in child2 class in c#.net.

If I understand from your question than you want to restrict Parent Class only need to be inherited by Only One Class and no other class need to be inherited from that class.

Simple Answer is No. This is not possible.

Simple rule is if you have make class public and method virtual then it can be inherited by n number of class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM