Can you explan anonymous type in usage of using statement?
Can you explan anonymous type in usage of using statement? can you explan pros and cons two kind of usage?
using(var myCtx = new Entity() )
{
}
Another:
using(Entity myCtx = new Entity() )
{
}
What's the differen开发者_运维知识库ce between them?
This is an implicitly typed variable, not an anonymous type. (An anonymous type is what you get using an expression such as new { X = 10, Y = "hello" }
.
Your two code snippets are exactly equivalent - the compiler is just inferring the type of myCtx
: it's still statically typed; the object will still be disposed etc.
There's nothing specific to the using
statement here - you can use implicit typing for any local variable, so long as the type you want is the same as the compile-time type of the initialization expression. (If the value is null
or an anonymous function, you'll need to cast the value, at which point it's reasonably pointless to use var
, to be honest.)
Blatant plug: you can find out more details of both implicit typing and anonymous types in chapter 8 of my book, C# in Depth. Fortunately, that's one of the free chapter's you can download from the Manning page for the book.
There is no difference between the IL produced for both statements, they're functionally identical. What you're doing here is letting the compiler infer the type of myCtx
, not creating an anonynous type. It can make code substantially clearer, for example:
var items = new Dictionary<int, Dictionary<int, string>>();
is clearer, and doesn't hide any of the intent of the code, than:
Dictionary<int, Dictionary<int, string>> items =
new Dictionary<int, Dictionary<int, string>>();
This isn't an anonymous type, it's jsut a syntax shortcut. As far as the compiler is concerned, the two statements are the same.
That's not actually anonymous type usage...it's inferred type usage. Using the var keyword simply "infers" the type on the left hand side of the assignment based on the right hand side of the assignment.
Pros:
- Eliminates redundancy (eg. MyType a = new MyType() is highly redundant and unnecessary)
Cons:
Obfuscates the code when used in certain scenarios (eg. var a = GetSomething(); --- what type is a? I don't know without looking at the return type of GetSomething())
You lose the ability for polymorphism when using var (you can't have MyParentType a = new MySubType()) - this isn't really a con, so much as an invalid use case for the var keyword.
My rule of thumb is that I like the var keyword, but only use it where it's intent is already explicit...that is, I use it when using the new keyword, but not for foreach loops or assignments based on the return value of a method.
精彩评论