CSharp mimicking JavaScript design pattern

来源:互联网 发布:程序员猝死 知乎 编辑:程序博客网 时间:2024/06/18 00:25

Simplest C# code so far I can think of equivalent to the JavaScript design pattern to allow private members.

The original JavaScript code can be found here:

http://www.crockford.com/javascript/private.html

For the ease of comparison, the JavaScript code from the above link is also pasted here,

function Container(param) {    function dec() {        if (secret > 0) {            secret -= 1;            return true;        } else {            return false;        }    }    this.member = param;    var secret = 3;    var that = this;    this.service = function () {        return dec() ? that.member : null;    };}

Following is the equivalent C# code,

class Program{class Container{// delegatesdelegate bool JsPrivateDelegate();public delegate dynamic ServiceDelegate();// constructorpublic Container(dynamic param){var secret = 3;JsPrivateDelegate dec = delegate(){if (secret <= 0) return false;secret--;return true;};Member = param;Service = () => dec() ? Member : null;}public dynamic Member { get; private set; } // public propertypublic ServiceDelegate Service { get; private set; }    // public 'method'}static void Main(string[] args){var c = new Container("haha");dynamic s;do{s = c.Service();    // consumes the serviceConsole.WriteLine("{0}", s ?? "<null>");} while (s != null);}}

Note the main point is make private members local variables as long as possible since they are accessible from the closure which C# fully supports. However as a strong-typed language, C# can't get rid of the delegate definition and the local variable definition needs to be in order within a method ('secret' has to come before 'dec').

原创粉丝点击