开发者

Why is there no "external" access modifier?

Maybe I'm missing something but shouldn't C# have an external access modifier for meth开发者_StackOverflowods? Ie an modifier that make an method public but only for other classes, ie the the method cannot be called by the class itself?

Wouldn't that be useful for things like public methods that do locking to ensure that the lock isn't reentred from within the class?


There's no need for it. Access control is used to restrict access to members from untrusted client code.

Remember that in OOP, a class represents an autonomous, self-contained unit of code and is implicitly assumed to be self-consistent.

If you can't trust the code in your own class not to cause reentrancy then what can you trust? It's impractical to guard against every possible eventuality with language features; sometimes it's just up to you as a developer to make sure your own code works :)


Interface methods with explicit implementation are probably the closest thing to what you want. Of course, a class could still call them on itself if it casts this to the interface type.


I think it wouldn't be useful. There is no paradigm that defines any need for it.

In your example: even if there is the external keyword how do you ensure that the lock cannot be re-entered externally without releasing it?

There are contracts between classes, and the class is always in a contract with itself. I think no keyword can help to avoid such programming mistakes. In this particular example, the class should implement the locking properly depending on its level of usage.


this is my pen on Typescript.

Maybe this can be useful for anybody to describe the problem wich can be solved by external access modifier

codepen

class ExternalUser {

  private static _time: number = 0;
  position: {x: number, y: number} = {x: 0, y: 0};

  constructor () {
    setInterval(this.bind(this.tick), 100);
  }

  external static set time(val: number) {
    ExternalUser._time = val;
  }

  static get time(): number {
    return ExternalUser._time;
  }

  private tick() {
    let someRandomThing = Math.random() > 0.95;
    if (someRandomThing) {
      ExternalUser.time += 100;// throws error, because set time is external
    }
    this.position={x: 10 * ExternalUser.time, y: ExternalUser.time * 10};
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜