开发者

How to write an extension method that returns a dynamic object?

I was thinking about how Regex.Match.Group wants to be dynamic:

Regex.Match (...).Groups["Foo"]

would like to be:

Regex.Match (...).Groups.Foo

I thought about writing an extension method that would allow:

Regex.Match (...).Groups().Foo

And tried writing it this way, but this isn't allowed (';' required by 'static dynamic')

public static dynamic DynamicGroups Groups(this Match match)
{
    return new DynamicGroups(match.Groups)开发者_运维问答;
}

public class DynamicGroups : DynamicObject
{
    private readonly GroupCollection _groups;

    public DynamicGroups(GroupCollection groups)
    {
        this._groups = groups;
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        Group g = this._groups[binder.Name];

        if (g == null)
        {
            result = null;
            return false;
        }
        else
        {
            result = g;
            return true;
        }
    }
}

Any way to accomplish this?

There are plenty of other APIs that were written before dynamic that might be cleaner to use this way.


There's just one little error in your code, change dynamic DynamicGroups to just dynamic

public static dynamic Groups(this Match match)
{
    return new DynamicGroups(match.Groups);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜