简体   繁体   English

C# 使用访问修饰符来限制对模拟的访问

[英]C# using access modifiers to bottleneck access to Simulation

I want to prevent that someone interacts with a simulation in a way that he shouldn't.我想防止有人以他不应该的方式与模拟交互。 The only allowed way is to implement a method of the Interface "IInteraction" and add this interaction to a list.唯一允许的方法是实现接口“IInteraction”的方法并将此交互添加到列表中。 The SimulationController then goes through this list and executes the method at an appropriate time. SimulationController 然后遍历这个列表并在适当的时间执行该方法。 So every class related to the simulation has to be accessible only by IInteraction (regardless from where IInteraction gets implemented).因此,与模拟相关的每个类都只能由 IInteraction 访问(无论 IInteraction 从何处实现)。

I tried to make the simulation class internal, as this would restrict anyone from accessing it.我试图将模拟类设为内部,因为这会限制任何人访问它。 But the Interaction needs a reference to the simulation to be able to manipulate it.但是交互需要对模拟的引用才能对其进行操作。 A reference to it is only possible inside the assembly of the Simulation, which makes this approach useless, because that way the implementation of IInterface can't be made from a public scope.对它的引用只能在 Simulation 的程序集中,这使得这种方法无用,因为这样 IInterface 的实现不能从公共范围进行。

IInteraction should be public. IInteraction应该是公开的。 But with the Simulation being internal, an implementation of IInteraction can't access it.但是由于Simulation是内部的,因此IInteraction的实现无法访问它。

The trick to this is to publish an interface ISimulation , letting IInteraction program to its interface.这个技巧是发布一个接口ISimulation ,让IInteraction编程到它的接口。 An internal implementation of ISimulation would remain hidden from IInteraction implementations. ISimulationinternal实现将对IInteraction实现隐藏。

public interface ISimulation {
    void SetSomethingUp();
    void DoSomething();
}
public interface IInteraction {
    void Process(ISimulator simulator);
}
...
internal class Simulator : ISimulator {
    public void SetSomethingUp() {
        ...
    }
    public void DoSomething() {
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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