If dynamic resolves to object at compile time, and all .NET types extend object, why does dynamic not act like an object with regards to IntelliSense? Whenever I use dynamic I get a message saying "dynamic expression. this will be resolved at runtime". Surely it should also display object members?
问题:
回答1:
Intellisense do not work in dynamic type. It is resolved at Runtime. Dynamic type work for static types as well as anonymous types.
If intellisense would have worked, it would have defied the very purpose of dynamicity.
I think you should read Jon Skeet answer about object vs dynamic
here
回答2:
I would suspect it doesn't provide these members because there could be an arbitrary number of overloads to any of the methods on object
- which it obviously can't know of at intellisense time. So it could be displaying the wrong intellisense information for a particular method invocation.
回答3:
Ultimately because all dynamic operations use dynamic dispatch, i.e. not compile-time linking, and therefore there really is no guarantee that any member will actually exist - even ToString
- because the dynamic layer of an object is free to intercept/replace/remove even the basic operations of object
. As a result, for the intellisense window to attempt to display anything would be disingenuous.
Yes it's compiled as object
, but that's more because (nearly) all objects are object
(or can be boxed as such) and so therefore the runtime knows that, whatever the dynamic object is, it can be held as an object reference.
But if you want to use the object
members, or if you want intellisense to show them, you'd have to cast to object
first - which in itself would be a dynamic operation as well.
That's not to say it's not possible to display intellisense members for dynamic languages, of course it is (I believe Iron Python can), it's just that in C# it's not - and reasonably so.