Howto write a class where a property can be accessed without naming it
I have a (dump) question regarding VB/C#
I often use third party classes where I can access a child object with only specifying the id or key.
Example:
Instead of writing:
DataRow row = GetAPopulatedDataRowSomeWhere();
Object result = row.Items[1]; // DataRow has no Items property
Object result = row.Items["colName"]; // Also not possible
I us开发者_如何学运维e this code to access the members:
DataRow row = GetAPopulatedDataRowSomeWhere();
Object result = row[1];
Object result = row["colName"];
Can someone tell me how a class has to look like to support this syntax? My own class has a Dictionary that I want to access this way.
MyClass["key"]; // <- that's what I want
MyClass.SubItems["key"]; // <- that's how I use it now
You need to have an indexed property.
public class MyClass
{
public object this[string key]
{
get { return SubItems[key]; }
set { SubItems[key] = value; }
}
}
精彩评论