Hi everyone,
Atfirst let me tell you, i don't think i am a very bad coder. Yes, i am not an extreme coder but i can code enough to make a system working.
Last few days i were given responsibility to automate an microsoft excel automation task. As the deadline was too short so i didn't go "Read manual-do the job" style....I directly searched in google, found some code segment and used those.
The code worked perfectly and it replaced our 9 hour workload with 3.2 minute only....I have managed to gather a relatively deep level knowledge on office automation through the task but today when i got leave, I tried to dig out details about the code that i missed due to directly copying+using from google.
The very first line creates all the problems......it is:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application application;
application= new Excel.Application();
Here Application is an interface..........Then how on earth i instantiate an inter开发者_如何学Cface ??? I couldn't figure out the solution. It's really killing me.
Interface can't be instantiated...Then why this code works ??? Anyone knows ???
Any reply will be appretiated.
The Excel.Application interface is declared in inter-op assembly. If you see its definition, the interface will be decorated with GUID and a CoClass attribute (CoClass(typeof(ApplicationClass))
). Because of this attribute, the code line
application= new Excel.Application();
will actually get translated into
application= new Excel.ApplicationClass();
ApplicationClass is a simple .NET class that has been decorated with interop attributes so that all calls (including construction) would be forwarded to actual COM component. Interop assemblies are typically get created importing the type library for COM components. Refer this article for more information on how com types get mapped to .NET types.
Edit: Just did a little bit of Googling for extra information to include in post and came across same question on SO. Especially check Eric Lippert's answer where he explains compiler's logic when new operator is used on interface.
精彩评论