如何防止基类的方法?

时间:2018-05-22 17:58:33

标签: c#

如何阻止方法1访问sub2类,方法2访问sub1类?

public class Main
{

    void Method1()       //prevent this method for sub2
    {
    }
    void Method2()//prevent this method for sub1
    {
    }
}

public class sub1: Main
{

}

public class sub2: Main
{

}

1 个答案:

答案 0 :(得分:1)

你不能。

你可以做的是添加另一层类 - Middle1和Middle2:

public class Main
{
    // All shared properties and methods here
}

public class Middle1 : Main
{
    public void Method1()  
}

public class Middle2 : Main
{
    public void Method2()  
}

public class Sub1 : Middle1
{
    // Don't have access to Method2()  
}

public class Sub2 : Middle2
{
    // Don't have access to Method1()  
}

或者直接在派生类中定义这些方法:

public class Main
{
    // All shared properties and methods here
}

public class Sub1 : Main
{
    public void Method1()  
}

public class Sub2 : Main
{
    public void Method2()  
}