CSharp mimicking JavaScript design pattern

28 篇文章 0 订阅
20 篇文章 0 订阅

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
	{
		// delegates
		delegate bool JsPrivateDelegate();
		public delegate dynamic ServiceDelegate();

		// constructor
		public 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 property
		public 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 service
			Console.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').

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值