开发者

Why can't an Anonymous Type be used outside the method it's created in?

I understand that if I cast it to a named type I can do whatever I want with it, but it'd make for much tidier code if I could keep the anonymity betw开发者_如何转开发een method calls.


Think of the signature of your method as a contract. Your method says "I promise to return you something that contains the following fields." If you return an anonymous object from your method, there's no contract. You're just saying "There's some data here, good luck!"

If C# 4 is at all an option, you can just use tuples to return somewhat more arbitrary data.


While it should be avoided because it isn't very clean, you might consider this hack from Jon Skeet. However, if at all possible, it should be avoided.


This is a guess...but I'm so "awesome" I'm "sure" I'm right...

Anonymous types really aren't "anonymous." The class that represents the unknown type is generated at run-time local to the method call on the run-time stack(hence the method-only scope). Returning from the function call(popping the stack) you lose all the objects in that scope including the anonymous class that was hiding on the stack with that method call.

Guessing over...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜