• CSharp mimicking JavaScript design pattern


    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').

  • 相关阅读:
    UITabBarController生命周期(使用storyoard搭建)
    ios应用数据存储方式(归档)
    ios应用数据存储方式(偏好设置)
    使用picker View控件完成一个简单的选餐应用
    ios应用数据存储方式(XML属性列表-plist)
    控制器的View的创建
    控制器的创建
    权限管理具体代码实现
    gitHub相关
    初始Ajax
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3091628.html
Copyright © 2020-2023  润新知