Does C# .NET support IDispatch late binding?

后端 未结 6 1173
情话喂你
情话喂你 2020-12-08 20:11

The Question

My question is: Does C# nativly support late-binding IDispatch?


Pretend i\'m trying to automate Office,

6条回答
  •  暖寄归人
    2020-12-08 21:01

    probably you can get away with much nicer code in in C# 2.0/3.0 if you take the time to write an interface containing the methods and properties you want of the object and add some attributes (i write it from memory, so details may not be correct, but i swear it worked for me...)

        using System.Runtime.Interopservices;
    
        [Guid("00024500-0000-0000-C000-000000000046")]
        [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
        interface IExcel
        {
          // sample property
          string Name{get;}
          // more properties
        }
    
        // and somewhere else
        void main()
        {
          Object xl = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
          IExcel excel = (IExcel)xl;
          string name = xl.name
        }
    

    As mentioned, the code will not work out of the box, it is more a hint what to dig for in msdn.

提交回复
热议问题