using System; using NXOpen; using NXOpen.Annotations; using NXOpen.UF;
namespace NXExpressionUpdate { class Program { static void Main(string[] args) { // 初始化NX环境 Session theSession = Session.GetSession(); UFSession theUFSession = UFSession.GetUFSession();
try
{
// 打开指定部件文件
string partPath = @"C:\Users\zhao.gang10\model.prt";
PartLoadStatus partLoadStatus;
Part workPart = theSession.Parts.OpenBaseDisplay(partPath, out partLoadStatus);
// 切换到工作部件上下文
theSession.Parts.SetWork(workPart);
// 获取表达式集合
Expression[] expressions = workPart.Expressions;
// 查找并修改表达式
bool found = false;
foreach (Expression exp in expressions)
{
if (exp.Name == "a1")
{
// 修改表达式值
exp.RightHandSide = "300";
found = true;
break;
}
}
if (!found)
{
throw new Exception("未找到名为a1的表达式");
}
// 更新模型并保存
workPart.Update();
workPart.Save(Part.SaveComponents.True, Part.CloseAfterSave.False);
Console.WriteLine("表达式a1已成功修改为300");
}
catch (Exception ex)
{
Console.WriteLine($"操作失败: {ex.Message}");
}
finally
{
// 清理资源
theSession.Dispose();
}
}
}
}