C#实现创建、编辑NX表达式

在NX8.5中使用C#编辑表达式中有个坑,part.Expressions.Edit该方法鲁棒性很差,当表达式有错时也能编辑成功(手动在NX中增加错误表达式会有弹框,无法创建,而该方法却可以,疑是bug),建议使用表达式对象的RightHandSide属性进行设置。错误的表达式导致对象在保存或者设为显示部件、工作部件时,NX报“Update undo happened”错误!

如下图:

 

一个简单的例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NXOpen;
using NXOpen.Utilities;
using NXOpen.UF;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Session theSession = Session.GetSession();
            UFSession theUfSession = UFSession.GetUFSession();
            UFUi theUFUi = theUfSession.Ui;

            string path = @"D:	est model\_asm1.prt";
            NXOpen.Tag obj = NXOpen.Tag.Null;
            UFPart.LoadStatus LoadStatus;
            theUfSession.Part.Open(path, out obj, out LoadStatus);
            NXOpen.Part part = theSession.Parts.Display;

            try
            {
                foreach (Expression p in part.Expressions)
                {
                    if ("a" == p.Name)
                    {
                        p.RightHandSide = "4";
                        //part.Expressions.Edit(p, "ab*cd*ef+5");
                        p.EditComment("测试");
                    }
                }

                //Expression exp = part.Expressions.Create("a=1");
               
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            theUfSession.Part.Save();
            theUfSession.Part.CloseAll();
        }
    }
}

创建表达式(part.Expressions.Create)方法和编辑表达式(RightHandSide)属性,当表达式错误时会抛出异常,使用try catch根据这点判断表达式是否正确。

作者:快雪
本文版权归作者所有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/kuaixue/p/13573935.html