System.Runtime.InteropServices.COMException:"Inappropriate source object for this action"。在检索连接的形状时被识别

System.Runtime.InteropServices.COMException: "Inappropriate source object for this action". is identified while retrieving the connected shapes

我正在尝试获取页面中每个形状的连接形状。但是我发现了一个奇怪的 COM 异常 - "Inappropriate source object for this action"

这是我的代码:

using Microsoft.Office.Interop.Visio;

class Program
{
  static void Main(string[] args)
  {
    Application visApp = new Application();
    Document visDoc = visApp.Documents.Open(filePath);

    // Get the first page in the sample drawing.
    page = visDoc.Pages[1];

    foreach (Microsoft.Office.Interop.Visio.Shape shp in page.Shapes)
    {               
        GetConnected(shp, Microsoft.Office.Interop.Visio.VisConnectedShapesFlags.visConnectedShapesOutgoingNodes, "", null, true);
    }
 }


    private static void GetConnected(Microsoft.Office.Interop.Visio.Shape shp, Microsoft.Office.Interop.Visio.VisConnectedShapesFlags whichConnectedShapes, string category, Microsoft.Office.Interop.Visio.Selection selection, bool addToSelection)
     {
        Array aryTargetIDs;

        //getting an exception here during the second iteration of for loop of Main method
        aryTargetIDs = shp.ConnectedShapes(whichConnectedShapes, category); 
     }
  }

ConnectedShapes 方法对 1D 形状(即连接器)抛出此异常。因此,您只需要在调用您的辅助方法之前或按照以下方式在其中包括此检查:

using Visio = Microsoft.Office.Interop.Visio

private static void GetConnected(
            Visio.Shape shp, 
            Visio.VisConnectedShapesFlags whichConnectedShapes, 
            string category, 
            Visio.Selection selection, 
            bool addToSelection)
{
    if (shp is null)
    {
        throw new ArgumentNullException();
    }
    if (shp.OneD == 0)
    {   
        Array aryTargetIDs = shp.ConnectedShapes(whichConnectedShapes, category);
        Console.WriteLine($"{shp.Master.Name} ({shp.NameID}) - {String.Join(", ", aryTargetIDs.Cast<object>().ToArray())}");
    }
}

所以给定一组这样的形状:

上述代码的控制台输出如下所示:

Start/End (Sheet.1) - 2
Decision (Sheet.2) - 4, 6
Subprocess (Sheet.4) - 
Document (Sheet.6) -