【问题标题】:Two projects, a derived class should be able to access one method but not the other one两个项目,派生类应该能够访问一个方法,但不能访问另一个
【发布时间】:2020-05-23 06:53:07
【问题描述】:

我在面试中被问到这个问题,但无法回答。

有两个项目:P1 和 P2

P1 有一个带有方法 M1 和 M2 的 A 类

P2 有一个 B 类和 C 类,这两个类(继承或引用)*来自项目 P1 中的 A 类

B 类应该能够访问方法 M1 但不能访问 M2 C 类应该能够访问方法 M2 但不能访问 M1

*我不记得他说的是继承还是参考

如何做到这一点?

【问题讨论】:

  • 请分享您的代码和课程
  • 我相信这是一个关于理解问题的问题,而不是关于实施它的问题。您拥有受保护、内部、接口等工具,但如果您的理解是您在 P1 中设置的内容阻止 P2 中的两个类执行您不希望它们执行的操作,那么不,你不能那样做。但是如果你想在 P2 中设计这两个类,使它们只能访问它们应该访问的方法,那么是的,你可以这样做,但这部分是在 P2 中完成的。
  • 这听起来像是一个措辞不佳的问题。从某种角度来看是不可能的。如果 B 类可以访问某个方法而 C 类不能,那么您可以随时更改 C 类中的代码,以便它执行 B 类所做的任何事情。这个问题暗示它是关于限制或阻止访问,但事实并非如此。 “应该能够访问”可能意味着任何事情。一个类允许或阻止对方法的访问。
  • 我在采访中的回答是,“你为什么要做这么奇怪和令人困惑的事情?”

标签: c# oop


【解决方案1】:

您想使用接口从类中提取方法。

P1:

public interface IM1
{
  void M1();
}

public interface IM2
{
  void M2();
}

// Not public
internal class A : IM1, IM2
{
   public void M1() {} 
   public void M2() {}
}

P2:

public class B
{
   private readonly IM1 _m1;
}

public class C
{
   private readonly IM2 _m2;
}

【讨论】:

  • 但是这里,B类和C类不是从A类继承的
  • @teenup 你在问题中提到了inherit or reference,这个答案使用参考方法。使用继承无法实现您想要实现的目标。
  • 我不确定这是否是解决方案。因为,即使面试官说“参考”,他也使用了陈述(参考 A),而不是单个接口。我希望对此有其他答案。
  • 这里如何从B类调用_m1?你能解释一下吗?
  • @teenup 无法使用继承隐藏函数。使用组合,你仍然引用 A,但只能访问它的接口部分(如果 A 是公共的,你可以更新它 (_m1 as A) != null)。您可以像任何其他常规对象一样调用_m1??
【解决方案2】:

你可以实现一些类似:https://dotnetfiddle.net/0mYxdU

public interface InterfaceCommon
{
    void Function();
}

public class Implementacion1 : InterfaceCommon
{
    public void Function()
    {
        Console.WriteLine("I am Method1");
    }
}

public class Implementacion2 : InterfaceCommon
{
    public void Function()
    {
        Console.WriteLine("I am Method2");
    }
}

public abstract class A
{
    private readonly InterfaceCommon interfaceCommon;

    protected A(InterfaceCommon interfaceCommon)
    {
        this.interfaceCommon = interfaceCommon;
    }

    public void  CallFunction()
    {
        interfaceCommon.Function();
    }

}


public class B : A
{
   public B() : base(new Implementacion1()) {  }

}

public class C : A
{
    public C() : base(new Implementacion2()) { }

}

public class Program
{
    public static void Main(string[] args)
    {
        var b = new B();
        b.CallFunction();
        var c = new C();
        c.CallFunction();
        Console.ReadLine();
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
  • 2020-03-07
  • 2021-12-11
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
相关资源
最近更新 更多