类的中括号取值

直接实例化使用

	public class ABC
	{
		string this[string key] 
		{ 
			get{ return "value"}
		}
	}

    static class Program
    {
        public static ABC  a= new ABC();
        static void Main(string[] args)
        {
            var c = a["0"]; //自定义类中括号取值
        }
    }


子类实例化,使用父类属性

	class Program
    {
        static void Main(string[] args)
        {
            var  test = new test_A();
            var a =  test["0"];
        }
    }
    
    class test_A:ABC {}
    
    class ABC
    {
        public  string this[string index] {
            get
            {
                return "";
            }
        }
    }

建造者模式示例

实例化后,直接接中括号填写参数

 vehicle["frame"] = "Car Frame"
 class Vehicle
    {
        private string _vehicleType;
        private Dictionary<string, string> _parts =
          new Dictionary<string, string>();

        // Constructor
        public Vehicle(string vehicleType)
        {
            this._vehicleType = vehicleType;
        }

        // Indexer
        public string this[string key]
        {
            get { return _parts[key]; }
            set { _parts[key] = value; }
        }

        public void Show()
        {
            Debug.Log("\n---------------------------");
            Debug.Log("Vehicle Type: " + _vehicleType);
            Debug.Log(" Frame : " + _parts["frame"]);
            Debug.Log(" Engine : " + _parts["engine"]);
            Debug.Log(" #Wheels: " + _parts["wheels"]);
            Debug.Log(" #Doors : " + _parts["doors"]);
        }
    }
    
class CarBuilder : VehicleBuilder
    {
    
    Vehicle vehicle;
    
        public CarBuilder()
        {
            vehicle = new Vehicle("Car");
        }

        public override void BuildFrame()
        {
            vehicle["frame"] = "Car Frame";
        }

        public override void BuildEngine()
        {
            vehicle["engine"] = "2500 cc";
        }

        public override void BuildWheels()
        {
            vehicle["wheels"] = "4";
        }

        public override void BuildDoors()
        {
            vehicle["doors"] = "4";
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值