首页 > 解决方案 > 如何使用 Marshal.CreateWrapperOfType(非过时版本)从 Com 对象转换为 Outlook 类型

问题描述

我有一段代码很适合我使用过时的函数。我将精简到最小的部分:

private dynamic pSentFolderItems; //will reference the Items of an Outlook Folder 

public void WatchEmail2(object app, string emailID)
{
    pApp = app; //this is actually an Outlook Application instance
    //below reference to the Items object comes back as ComObject
    pSentFolderItems = pApp.Session.GetDefaultFolder(5).Items;

    //get the type through Reflection on the instance
    Type olItemsType = pApp.GetType().Assembly.GetType("Microsoft.Office.Interop.Outlook.ItemsClass", false, true);

    //pSentFolderItems = Marshal.CreateWrapperOfType(pSentFolderItems, olItemsType);
    //above works every time but is marked Obsolete!!
    //http://go.microsoft.com/fwlink/?LinkID=296519

    //I'm struggling to implement the generic version of the CreateWrapperOfType method, as errors occur
    //and I cannot input the type parameters without errors
    pSentFolderItems = Marshal.CreateWrapperOfType<ShouldBeComObjectType, ShouldBeOlItemsType>(pSentFolderItems);

    //.....rest of code........
}

这是VB代码:

Public Class OVBO
    Private pApp As Object
    Public pMailId As String = ""
    Public itemSent As Boolean = False  'change to a map?
    Public itemWatching As Boolean = False

    Public pSentFolderItems As Object

    Public Sub WatchEmail2(app As Object, emailID As String)
        pMailId = emailID
        pApp = app

        If Not itemWatching Then
            pSentFolderItems = pApp.Session.GetDefaultFolder(5).Items

            Dim olType As Type = pApp.GetType().Assembly.GetType("Microsoft.Office.Interop.Outlook.ItemsClass", False, True)
            Dim myFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic
            Dim evt As EventInfo = olType.GetEvent("ItemAdd", myFlags)
            Dim evtHandlerType As Type = evt.EventHandlerType

            Dim finalD As [Delegate] = [Delegate].CreateDelegate(evtHandlerType, Me, "MailSent2")
            Dim addHandlerArgs() As Object = {finalD}

            'The below works to return an Items Object(from a ComObject) that can be passed to the method handler invocation
            pSentFolderItems = Marshal.CreateWrapperOfType(pSentFolderItems, olType)
            'The above is obsolete, and am struggling to work with the non-obsolete method at [MSDN][1]

            Dim miAddHandler As MethodInfo = evt.GetAddMethod()
            miAddHandler.Invoke(pSentFolderItems, addHandlerArgs)

            itemWatching = True
        End If

        Console.WriteLine("Watching {0}", emailID)
    End Sub

    'rest of class
End Class

请注意,没有对 Outlook dll 的引用,也没有对互操作的引用。

所以我想知道是否有人可以帮助将过时的方法调用转换为新方法。

标签: c#.netvb.netcom

解决方案


推荐阅读