用一个小程序重新认识“&”与“&&”

mac2022-06-30  158

上午写了个提CAD PL拐点的程序,很简单,但是遇到提示选择时用esc取消CAD就会报错。程序如下:

代码 using System; using System.Text; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using System.IO;[assembly:CommandClass( typeof (提拐点坐标.Class1))] /* Copyright © 519 2008AutoCAD version:AutoCAD 2008Description:To use 提拐点坐标.dll:1. Start AutoCAD and open a new drawing.2. Type netload and select 提拐点坐标.dll.3. Execute the Test command.Autodesk references added to this project are acdbmgd.dll,acmgd.dll. */ namespace 提拐点坐标{ /// <summary> /// Summary for Class1. /// </summary> public class Class1:IExtensionApplication { public void Initialize() { Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage( " \n调试程序命令GD " ); // 初始化操作 } public void Terminate() { // 清除操作 } Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Database db = Autodesk.AutoCAD.DatabaseServices.HostApplicationServices.WorkingDatabase; Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = Autodesk.AutoCAD.DatabaseServices.HostApplicationServices.WorkingDatabase.TransactionManager; [CommandMethod( " GD " )] public void Test() { try { Transaction trans = tm.StartTransaction(); using (trans) { BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); PromptSelectionOptions ps = new PromptSelectionOptions(); ps.MessageForAdding = " 选择要提取的多段线 " ; TypedValue[] filter = { new TypedValue( 0 , " LWPOLYLINE " ) }; PromptSelectionResult sr = ed.GetSelection(ps, new SelectionFilter(filter)); if (sr.Status == PromptStatus.OK && sr.Value.Count != 0 ) { StreamWriter sw = new StreamWriter( @" c://点坐标.txt " ); ObjectId[] ss = sr.Value.GetObjectIds(); foreach (ObjectId obj in ss) { Polyline pl = (Polyline)trans.GetObject(obj, OpenMode.ForRead); int vn = pl.NumberOfVertices; for ( int i = 0 ; i < vn; i ++ ) { Point3d pt3d = pl.GetPoint3dAt(i); sw.WriteLine(pt3d.ToString()); } } sw.Close(); System.Diagnostics.Process.Start( " notepad.exe " , @" c://点坐标.txt " ); } } } finally { } } }}

 

主程序没有问题,程序中能报错的地方只有if (sr.Status == PromptStatus.OK & sr.Value.Count != 0)这句,如果选择被取消sr.Status应该为PromptStatus.Cancel,sr.Status == PromptStatus.OK 这句没有问题,如果有问题就可能出现再sr.Value.Count != 0这句。即如果程序判断出sr.Status == PromptStatus.OK为false仍然要执行sr.Value.Count != 0这句的话CAD就会报错。

查看MSDN上关于“&”的解释为:& 运算符计算两个运算符,与第一个操作数的值无关。

再查看关于“&&”的解释:

x && y

对应于操作

x & y

不同的是,如果 x 为 false,则不计算 y(因为不论 y 为何值,“与”操作的结果都为 false)。这被称作为“短路”计算。

不能重载条件“与”运算符,但常规逻辑运算符和运算符 true 与 false 的重载,在某些限制条件下也被视为条件逻辑运算符的重载。

转载于:https://www.cnblogs.com/chinaHunk/articles/1890523.html

最新回复(0)