有没有办法在子类中隐藏部分方法?

Ram*_*Vel 6 c# inheritance interface

这个问题看起来很奇怪,但我最近在一次采访中遇到了这个问题.

有人问过,c#中是否有一种方法可以将方法部分隐藏在继承的子类中?假设基类A,暴露4种方法.B类实现A,它只能访问前2个方法,而C类实现A只能访问最后2个方法.

我知道我们可以这样做

public interface IFirstOne
{
    void method1();        
    void method2();
}

public interface ISecondOne
{
    void method3();
    void method4();
}

class baseClass : IFirstOne, ISecondOne
{
    #region IFirstOne Members

    public void method1()
    {
        throw new NotImplementedException();
    }

    public void method2()
    {
        throw new NotImplementedException();
    }

    #endregion

    #region ISecondOne Members

    public void method3()
    {
        throw new NotImplementedException();
    }

    public void method4()
    {
        throw new NotImplementedException();
    }

    #endregion
}

class firstChild<T> where T : IFirstOne, new()
{
    public void DoTest() 
    {

        T objt = new T();
        objt.method1();
        objt.method2();
    }
}


class secondChild<T> where T : ISecondOne, new()
{
    public void DoTest() 
    {
        T objt = new T();
        objt.method3();
        objt.method4();
    }
}
Run Code Online (Sandbox Code Playgroud)

但他们想要的是不同的.他们希望隐藏这些类继承自基类.这样的事情

class baseClass : IFirstOne, ISecondOne
{
    #region IFirstOne Members

    baseClass()
    {
    }

    public void method1()
    {
        throw new NotImplementedException();
    }

    public void method2()
    {
        throw new NotImplementedException();
    }

    #endregion

    #region ISecondOne Members

    public void method3()
    {
        throw new NotImplementedException();
    }

    public void method4()
    {
        throw new NotImplementedException();
    }

    #endregion
}

class firstChild : baseClass.IFirstOne //I know this syntax is weird, but something similar in the functionality
{
    public void DoTest() 
    {
        method1();
        method2();

    }
}


class secondChild : baseClass.ISecondOne
{
    public void DoTest() 
    {           
        method3();
        method4();
    }
}
Run Code Online (Sandbox Code Playgroud)

在c#中有没有办法可以实现这样的......

the*_*oop 2

尽管您不能完全按照您想要的方式进行操作,但您可以使用显式接口实现来提供帮助,其中接口成员仅在显式转换为该接口时才会公开...