开发者

Disadvantages of using anonymous types in place of dictionaries?

I wrote this function

    private string BuildXPathQuery(string prefix = "descendant::", string tag = "*", object attrs = null)
    {
        StringBuilder sb = new StringBuilder(prefix);
        sb.Append(tag);
        if (attrs != null)
            foreach (var a in attrs.GetType().GetProperties())
          开发者_运维问答      sb.Append(string.Format("[@{0}='{1}']", a.Name, a.GetValue(attrs, null)));
        return sb.ToString();
    }

So that instead of writing

 BuildXPathQuery(attrs: new Dictionary<string,string> {{"attr","value"}});

I could write

BuildXPathQuery(attrs: new {attr=value});

But does this have any drawbacks?


It uses reflection which might be slower than normal type access. Another drawback is that from looking at the method signature you see an object and for an eventual consumer of this method it might not always be evident as to what it has to put there because object can literally be anything:

When Intellisense shows:

BuildXPathQuery(object attrs);

you really have to guess here unless it is pretty well documented (for example ASP.NET MVC HTML helpers use similar approach to build HTML attributes on DOM elements).

It's a so much Rubyist approach that I like it :-) (optional arguments and hash tables)


I think Annonymous types are cool and you can easily cast it to appropriate object based on the object you send.

You can use this annonymous type to the method and also use it through reflection. You can also try to cast the object into the Type if you wish using :

var x = attrs as new{x="", y=""};

You should note, the compiler is smart enough to use the existing annonymous type rather than creating a new type for the casting.

http://www.west-wind.com/weblog/posts/189329.aspx

As already spoken, annonymous types are slower, so the only problem I can see is the slow performance. But annonymous looks cool to me.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜