Define Object indexer
"this" keyword + [ ] is used for defining a object indexer.Take this as a example,you'll get a more complete example shortly.
class yourCls{ public object this[String passIn] // Declare Indexer. { get{} set{} } } yourCls indexerCls = new indexerCls(); indexerCls["ObjectIndexer"] = "Sample"; //you can using indexer like this.Example with Collection
This example is using Collection in .Net Framework to implement Get or Set Properties dynamically.
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; namespace ObjectindexerWithCollection { class DynamicProperties { public Dictionary<string, string> hData = new Dictionary<string, string>(); //Declare dictionary to handler properties. public string this[string parameterName] { get { return this.hData[parameterName]; } set { this.hData[parameterName] = value; } } } class Program { static void Main(string[] args) { DynamicProperties lbx = new DynamicProperties(); lbx["test"] = "Object "; //set Indexer lbx["test1"] = "Indexers";//set Indexer Console.WriteLine("Here is the sample of {0}{1}", lbx["test"], lbx["test1"]); //get Indexer Console.ReadLine(); } } }
Example Output
This C# feature is useful at advanced C# software development. Just take as a note.Its can be using to design internal the "software pattern", you also can Apply in your software depend on your creative thinking.
No comments:
Post a Comment