开发者

Howto write a class where a property can be accessed without naming it

开发者 https://www.devze.com 2022-12-24 19:01 出处:网络
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.

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; }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消