我试图获取页面中每个形状的连接形状。但我发现一个奇怪的COM异常 - “此操作的不适当的源对象”
这是我的代码:
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) -