Dynamic, Object, Var
With the inception of the dynamic
type and the DLR in .NET 4, I now have 3 options when declaring what I call "open" types:
var
, locally implicit types to emphasize the 'what' instead of the 'how',object
, alias forSystem.开发者_Python百科Object
, anddynamic
, disable compiler checks, adding methods/properties at runtime
While there's a lot written about these out there, nothing I've found puts them together, and I have to confess, it's still a bit fuzzy.
Add to this LINQ, lambda expressions, anonymous types, reflection... and it gets more shaky.
I'd like to see some examples, perhaps contrasting advantages/disadvantages, to help me solidify my grasp of these concepts, as well as help me understand when, where and how I should pick between them.
Thank you!
Use
var
to keep your code short and more readable, or when working with anonymous types:var dict = new Dictionary<int, List<string>>(); var x = db.Person.Select(p => new { p.Name, p.Age });
Use
dynamic
when dynamic binding is useful, or required. Or when you need to decide which method to call based on the runtime type of the object.Use
object
as little as possible, prefer using specific types or generics. One place where it's useful is when you have object used just for locking:object m_lock = new object(); lock (m_lock) { // do something }
var
is exactly the same as writing the full type, so use that when a variable should be of a single type. It is often used with LINQ since you often use anonymous types with LINQ.
object
is the root of all classes, and so should be used when a variable will have many different, unrelated/not inherited instances, or when you do not know the type ad compile time (e.g. reflection). It's use should generally be avoided if possible.
dynamic
is for objects that are dynamic in nature, in that they can have different methods and properties, these are useful for interacting with COM as well as dynamic languages and domain specific languages.
var
: I use it for keeping code short:
instead of writing:
MyFramework.MyClass.MyType myvar = new MyFramework.MyClass.MyType();
i can keep it "short":
var myVar = new MyFramework.MyClass.MyType();
var
is statically type so the Type
is known at compile and runtime (so helps catch typos)
dynamic
very much similar to objects but not limited as it would be with the Object
methods, here the Type
is inferred at runtime, it would be used in cases wherein you want to achieve some dynamic behaviour.
Well for object
it ain't having any such members which you would be using, Generics would be more preferred in such cases
Have look on this article it gives advantages and limitations of Dynamic keyword.
精彩评论