.NET4.0新功能之String.IsNullOrWhiteSpace() 方法

本文介绍.NET Framework 4.0中新增的功能,包括动态语言支持、复数和大数运算、元组类型及文件系统枚举方法等,并重点介绍了新增的String.IsNullOrWhiteSpace()方法,展示了其用法及实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

在.NET Framework 4.0  中新增加了一些很方便的功能,比如:System.Dynamic支持动态语言运行时、System.Numerics.Complex 复数、System.Numerics.BigInteger 大数、System.Tuple 对象、遍历文件夹下文件夹和文件的新方法Directory.EnumerateDirectories、Directory.EnumerateFiles、Directory.EnumerateFileSystemEntries等,详细的新功能列表可以参考下面的链接:

http://msdn.microsoft.com/en-us/library/ms171868(VS.100).aspx

同时,还否定了一些原先的功能,这些过时的内容可以参考

http://msdn.microsoft.com/en-us/library/ee461502%28VS.100%29.aspx

下面就是.NET 4.0中新增加的String.IsNullOrWhiteSpace() 方法,方便用户对字符串进行处理。

C# 代码
using System;
class TestNET4
{
  
static void Main()
  {
    String[] TestString
= { null , String.Empty, " " , "   " , " abc " , " /t " , " /r/n " , " /v " , " /f " , " /a " };
    
for ( int i = 0 ; i < TestString.Length; i ++ )
    {
      String temp
= TestString[i];
      
if (temp == null )
      {
        Console.WriteLine(
" null IsNullOrWhiteSpace = "
                    
+ String.IsNullOrWhiteSpace(temp).ToString());
      }
      
else
      {
        Console.WriteLine(temp
+ " Length= " + temp.Length.ToString()
              
+ " IsNullOrWhiteSpace = "
              
+ String.IsNullOrWhiteSpace(temp).ToString());
      }
    }
  }
}

程序执行结果:

 null IsNullOrWhiteSpace = True
 Length=0 IsNullOrWhiteSpace = True
  Length=1 IsNullOrWhiteSpace = True
  Length=1 IsNullOrWhiteSpace = True
abc  Length=4 IsNullOrWhiteSpace = False
         Length=1 IsNullOrWhiteSpace = True

 Length=2 IsNullOrWhiteSpace = True
Length=1 IsNullOrWhiteSpace = True
Length=1 IsNullOrWhiteSpace = True
 Length=1 IsNullOrWhiteSpace = False

 

IsNullOrWhiteSpace方法的具体实现代码为:

C# 代码
public static bool IsNullOrWhiteSpace( string value)
{
    
if (value != null )
    {
        
for ( int i = 0 ; i < value.Length; i ++ )
        {
            
if ( ! char .IsWhiteSpace(value[i]))
            {
                
return false ;
            }
        }
    }
    
return true ;
}

所以,他是通过判断char.IsWhiteSpace方法来实现的,有些特殊字符也被当作空白字符,这一点特别注意注意,比如全角空格。

using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.Colors; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; public class CADUtilities { // 常量定义 - 使用固定重叠阈值 private const double OverlapThreshold = 10.0; // 毫米 // ================== 梁信息类 ================== private class BeamInfo { public string Size { get; set; } public int Count { get; set; } public double Width { get; set; } public double Height { get; set; } public double Area { get; set; } public double LineLoad { get; set; } } // ================== CLN - 清理无用实体命令 ================== [CommandMethod("CLN")] public void CleanUpDrawing() { Document doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) return; Database db = doc.Database; Editor ed = doc.Editor; using (Transaction tr = db.TransactionManager.StartTransaction()) { try { BlockTableRecord btr = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForWrite); int deletedCount = 0; var idsToDelete = new List<ObjectId>(); // 第一遍:收集需要删除的实体 foreach (ObjectId id in btr) { DBText text = tr.GetObject(id, OpenMode.ForRead) as DBText; if (text != null) { string textStr = text.TextString; // 保护轴号和标高文本 if (IsAxisNumber(textStr) || textStr.Contains("标高")) continue; // 删除空文本和无效梁标注 if (string.IsNullOrWhiteSpace(textStr) || (!IsBeamDimension(textStr) && !IsBeamLabel(textStr))) { idsToDelete.Add(id); } continue; } // 检查零长度线 Line line = tr.GetObject(id, OpenMode.ForRead) as Line; if (line != null && line.Length < 0.001) { idsToDelete.Add(id); } } // 第二遍:执行删除 foreach (ObjectId id in idsToDelete) { Entity ent = (Entity)tr.GetObject(id, OpenMode.ForWrite); ent.Erase(); deletedCount++; } tr.Commit(); ed.WriteMessage($"\n清理完成,删除 {deletedCount} 个无用实体"); } catch (System.Exception ex) { ed.WriteMessage($"\n错误: {ex.Message}"); tr.Abort(); } } } // ================== DEL - 图层删除命令 ================== [CommandMethod("DEL")] public void DeleteByLayer() { Document doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) return; Database db = doc.Database; Editor ed = doc.Editor; // 用户选择参考对象 PromptEntityOptions opt = new PromptEntityOptions("\n选择图层参考对象:"); PromptEntityResult res = ed.GetEntity(opt); if (res.Status != PromptStatus.OK) return; using (Transaction tr = db.TransactionManager.StartTransaction()) { try { // 获取目标图层 Entity refEnt = tr.GetObject(res.ObjectId, OpenMode.ForRead) as Entity; if (refEnt == null) return; string targetLayer = refEnt.Layer; // 收集当前空间所有实体 BlockTableRecord btr = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForWrite); List<ObjectId> toDelete = new List<ObjectId>(); foreach (ObjectId id in btr) { Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity; if (ent != null && ent.Layer == targetLayer) { toDelete.Add(id); } } // 执行删除 if (toDelete.Count > 0) { foreach (ObjectId id in toDelete) { Entity ent = (Entity)tr.GetObject(id, OpenMode.ForWrite); ent.Erase(); } tr.Commit(); ed.WriteMessage($"\n已删除图层 '{targetLayer}' 中的 {toDelete.Count} 个对象"); } else { ed.WriteMessage($"\n图层 '{targetLayer}' 中未找到可删除对象"); } } catch (System.Exception ex) { ed.WriteMessage($"\n错误: {ex.Message}"); tr.Abort(); } } } // ================== BLD - 梁原位标注引线修复命令 ================== [CommandMethod("BLD")] public void BeamAnnotationLeaderFix() { Document doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) return; Database db = doc.Database; Editor ed = doc.Editor; // 获取距离阈值 double distanceThreshold = GetDistanceThresholdFromEditor(); if (distanceThreshold < 0) // 用户取消 { ed.WriteMessage("\n操作已取消"); return; } // 定义梁图层关键词 string[] beamLayers = { "梁", "BEAM", "B-", "STRUCTURE" }; // 扫描梁实体和标注文本 List<BeamInfo> beamInfos = new List<BeamInfo>(); List<DBText> dimensionTexts = new List<DBText>(); using (Transaction tr = db.TransactionManager.StartTransaction()) { try { BlockTableRecord btr = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForRead); foreach (ObjectId id in btr) { Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity; if (ent == null) continue; string layer = ent.Layer?.ToUpper() ?? ""; // 识别梁实体 if (beamLayers.Any(l => layer.Contains(l)) && IsBeamEntity(ent)) { Extents3d extents = ent.GeometricExtents; Vector3d dir = GetBeamDirection(ent); bool isHorizontal = Math.Abs(dir.X) > Math.Abs(dir.Y); beamInfos.Add(new BeamInfo { Id = id, Extents = extents, Direction = dir, Center = new Point3d( (extents.MinPoint.X + extents.MaxPoint.X) / 2, (extents.MinPoint.Y + extents.MaxPoint.Y) / 2, 0), IsHorizontal = isHorizontal }); } // 只收集纯尺寸标注文本 if (ent is DBText text && IsPureBeamDimension(text.TextString)) { dimensionTexts.Add(text); } } tr.Commit(); ed.WriteMessage($"\n找到 {beamInfos.Count} 个梁实体和 {dimensionTexts.Count} 个尺寸标注"); ed.WriteMessage($"\n使用距离阈值: {distanceThreshold} mm"); ed.WriteMessage($"\n使用固定重叠检测阈值: {OverlapThreshold} mm"); } catch (System.Exception ex) { ed.WriteMessage($"\n扫描错误: {ex.Message}"); tr.Abort(); return; } } // 开始修复引线 int leaderCount = 0; int skippedDistanceCount = 0; int skippedOverlapCount = 0; List<Line> createdLeaders = new List<Line>(); // 存储已创建的引线 using (Transaction tr = db.TransactionManager.StartTransaction()) { try { BlockTableRecord btr = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForWrite); foreach (DBText text in dimensionTexts) { Point3d textPos = text.Position; // 查找最近的梁 BeamInfo targetBeam = FindTargetBeam(textPos, beamInfos); if (targetBeam == null) continue; // 获取梁上的锚点 Point3d beamPoint = GetBeamAnchorPoint(textPos, targetBeam); // 计算距离 double distance = textPos.DistanceTo(beamPoint); // 检查距离是否小于等于阈值 if (distance <= distanceThreshold) { skippedDistanceCount++; continue; } // 创建引线对象 Line leader = new Line(textPos, beamPoint); // 检查重叠 if (CheckLeaderOverlap(leader, createdLeaders)) { skippedOverlapCount++; continue; // 存在重叠,跳过创建 } // 配置并添加引线 ConfigureLeader(leader); btr.AppendEntity(leader); tr.AddNewlyCreatedDBObject(leader, true); createdLeaders.Add(leader); // 添加到已创建列表 leaderCount++; } tr.Commit(); ed.WriteMessage($"\n成功创建 {leaderCount} 条梁尺寸标注引线"); ed.WriteMessage($"\n跳过 {skippedDistanceCount} 条距离≤{distanceThreshold}mm的标注"); ed.WriteMessage($"\n跳过 {skippedOverlapCount} 条存在重叠的标注"); } catch (System.Exception ex) { ed.WriteMessage($"\n引线创建错误: {ex.Message}"); tr.Abort(); } } } // ================== 辅助方法实现 ================== // 识别轴号文本 private bool IsAxisNumber(string text) { if (string.IsNullOrWhiteSpace(text)) return false; return Regex.IsMatch(text, @"^[A-Za-z]?[\d]+[A-Za-z]?$") || Regex.IsMatch(text, @"^[A-Za-z]-?\d+$") || Regex.IsMatch(text, @"^\d+[A-Za-z]?$"); } // 识别梁尺寸标注 private bool IsBeamDimension(string text) { if (string.IsNullOrWhiteSpace(text)) return false; return Regex.IsMatch(text, @"\d{2,4}[×xX]\d{2,4}"); } // 识别梁编号标注 private bool IsBeamLabel(string text) { if (string.IsNullOrWhiteSpace(text)) return false; return text.Contains("L") || text.Contains("B") || text.Contains("KL") || text.Contains("XL"); } // 识别纯梁尺寸标注 private bool IsPureBeamDimension(string text) { if (string.IsNullOrWhiteSpace(text)) return false; return Regex.IsMatch(text, @"^\d{2,4}[×xX]\d{2,4}$"); } // 识别梁实体 private bool IsBeamEntity(Entity ent) { if (ent == null) return false; return ent is Line || ent is Polyline; } // 获取梁方向向量 private Vector3d GetBeamDirection(Entity beam) { if (beam is Line line) return line.EndPoint - line.StartPoint; if (beam is Polyline pline && pline.NumberOfVertices >= 2) return pline.GetPoint3dAt(1) - pline.GetPoint3dAt(0); return new Vector3d(1, 0, 0); } // 查找目标梁方法 private BeamInfo FindTargetBeam(Point3d textPos, List<BeamInfo> beams) { if (beams == null || beams.Count == 0) return null; BeamInfo bestBeam = null; double minDistance = double.MaxValue; foreach (BeamInfo beam in beams) { // 水平梁:只考虑上方梁 if (beam.IsHorizontal) { if (beam.Extents.MinPoint.Y > textPos.Y) { double distY = beam.Extents.MinPoint.Y - textPos.Y; double distX = Math.Abs(textPos.X - beam.Center.X); double distance = distY + distX * 0.1; if (distance < minDistance) { minDistance = distance; bestBeam = beam; } } } // 垂直梁:只考虑左侧梁 else { if (beam.Extents.MaxPoint.X < textPos.X) { double distX = textPos.X - beam.Extents.MaxPoint.X; double distY = Math.Abs(textPos.Y - beam.Center.Y); double distance = distX + distY * 0.1; if (distance < minDistance) { minDistance = distance; bestBeam = beam; } } } } return bestBeam; } // ================== 命令行输入距离阈值 ================== private double GetDistanceThresholdFromEditor() { Document doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) return 2000; // 默认值 Editor ed = doc.Editor; // 创建输入提示 PromptDoubleOptions pdo = new PromptDoubleOptions( "\n请输入原位标注的梁位置距梁边线最小距离,默认值为 <2000mm>: 根据需要输入"); // 设置提示选项 pdo.AllowNegative = false; // 不允许负数 pdo.AllowZero = false; // 不允许零值 pdo.DefaultValue = 2000; // 默认值 pdo.UseDefaultValue = true; // 允许使用默认值 // 获取用户输入 PromptDoubleResult pdr = ed.GetDouble(pdo); // 处理结果 if (pdr.Status == PromptStatus.OK) { return pdr.Value; } return -1; // 表示取消 } // 获取梁上的锚点(引线连接点) private Point3d GetBeamAnchorPoint(Point3d textPos, BeamInfo beam) { if (beam.IsHorizontal) { return new Point3d(textPos.X, beam.Extents.MinPoint.Y, 0); } else { return new Point3d(beam.Extents.MaxPoint.X, textPos.Y, 0); } } // 检查引线是否与现有引线重叠 private bool CheckLeaderOverlap(Line newLeader, List<Line> existingLeaders) { // 创建新引线的边界框(带缓冲) Extents3d newExtents = GetExtendedExtents(newLeader, OverlapThreshold); foreach (Line existingLeader in existingLeaders) { // 快速边界框检查 if (!ExtentsOverlap(newExtents, existingLeader.GeometricExtents)) continue; // 精确距离检查 double distance = GetLineDistance(newLeader, existingLeader); if (distance <= OverlapThreshold) { return true; // 存在重叠 } } return false; // 没有重叠 } // 检查两个边界框是否重叠 private bool ExtentsOverlap(Extents3d ext1, Extents3d ext2) { return ext1.MinPoint.X <= ext2.MaxPoint.X && ext1.MaxPoint.X >= ext2.MinPoint.X && ext1.MinPoint.Y <= ext2.MaxPoint.Y && ext1.MaxPoint.Y >= ext2.MinPoint.Y; } // 计算两条线之间的最小距离 private double GetLineDistance(Line line1, Line line2) { // 计算线1上点到线2的最短距离 double minDistance = double.MaxValue; // 检查线1的两个端点到线2的距离 minDistance = Math.Min(minDistance, GetPointToLineDistance(line1.StartPoint, line2)); minDistance = Math.Min(minDistance, GetPointToLineDistance(line1.EndPoint, line2)); // 检查线2的两个端点到线1的距离 minDistance = Math.Min(minDistance, GetPointToLineDistance(line2.StartPoint, line1)); minDistance = Math.Min(minDistance, GetPointToLineDistance(line2.EndPoint, line1)); return minDistance; } // 计算点到线的最短距离 private double GetPointToLineDistance(Point3d point, Line line) { // 获取线的起点和终点 Point3d start = line.StartPoint; Point3d end = line.EndPoint; // 计算向量 Vector3d lineVec = end - start; Vector3d pointVec = point - start; // 计算投影长度 double lineLength = lineVec.Length; double dotProduct = pointVec.DotProduct(lineVec); double projection = dotProduct / (lineLength * lineLength); // 限制投影在0-1之间 projection = Math.Max(0, Math.Min(1, projection)); // 计算最近点 Point3d closestPoint = start + lineVec * projection; // 返回距离 return point.DistanceTo(closestPoint); } // 获取扩展后的边界框(用于快速碰撞检测) private Extents3d GetExtendedExtents(Line line, double buffer) { Point3d min = new Point3d( Math.Min(line.StartPoint.X, line.EndPoint.X) - buffer, Math.Min(line.StartPoint.Y, line.EndPoint.Y) - buffer, 0); Point3d max = new Point3d( Math.Max(line.StartPoint.X, line.EndPoint.X) + buffer, Math.Max(line.StartPoint.Y, line.EndPoint.Y) + buffer, 0); return new Extents3d(min, max); } // 配置引线属性 private void ConfigureLeader(Entity leader) { leader.Layer = "标注"; leader.ColorIndex = 2; // 黄色 leader.Linetype = "Continuous"; leader.LineWeight = LineWeight.LineWeight013; } // ================== BSTAT - 梁截面尺寸统计命令 ================== [CommandMethod("BST")] public void BeamStatisticsSortedByLoad() { Document doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) return; Database db = doc.Database; Editor ed = doc.Editor; // 提示用户框选范围 PromptSelectionOptions pso = new PromptSelectionOptions(); pso.MessageForAdding = "\n框选要统计的梁实体和标注文本: "; PromptSelectionResult psr = ed.GetSelection(pso); if (psr.Status != PromptStatus.OK) return; // 定义梁尺寸正则表达式 Regex sizeRegex = new Regex(@"(\d+)[xX×](\d+)", RegexOptions.Compiled); // 存储原始尺寸统计结果 Dictionary<string, int> sizeCounts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); using (Transaction tr = db.TransactionManager.StartTransaction()) { try { // 处理选中的实体 foreach (ObjectId id in psr.Value.GetObjectIds()) { Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity; if (ent == null) continue; // 处理文本实体 if (ent is DBText text) { string textStr = text.TextString; Match match = sizeRegex.Match(textStr); if (match.Success) { string size = $"{match.Groups[1].Value}x{match.Groups[2].Value}"; AddSizeToDictionary(sizeCounts, size); } } // 处理多行文本 else if (ent is MText mtext) { string textStr = mtext.Text; MatchCollection matches = sizeRegex.Matches(textStr); foreach (Match match in matches) { string size = $"{match.Groups[1].Value}x{match.Groups[2].Value}"; AddSizeToDictionary(sizeCounts, size); } } } // 如果没有找到尺寸信息 if (sizeCounts.Count == 0) { ed.WriteMessage("\n未找到有效的梁尺寸信息!"); tr.Abort(); return; } // 提示用户输入表格插入点 PromptPointOptions ppo = new PromptPointOptions("\n指定统计表插入点: "); PromptPointResult ppr = ed.GetPoint(ppo); if (ppr.Status != PromptStatus.OK) return; Point3d insertPoint = ppr.Value; // 创建并排序梁尺寸信息列表 List<BeamSizeInfo> sortedBeamInfo = CreateSortedBeamInfo(sizeCounts); // 创建统计表格 CreateBeamStatisticsTable(tr, db, insertPoint, sortedBeamInfo); tr.Commit(); ed.WriteMessage($"\n已创建包含 {sizeCounts.Count} 种梁尺寸的统计表,按线荷载值降序排列"); } catch (System.Exception ex) { ed.WriteMessage($"\n错误: {ex.Message}"); tr.Abort(); } } } // 添加尺寸到字典的辅助方法 private void AddSizeToDictionary(Dictionary<string, int> dict, string size) { if (dict.ContainsKey(size)) { dict[size]++; } else { dict[size] = 1; } } // 创建并排序梁尺寸信息 - 确保所有路径都有返回值 private List<BeamSizeInfo> CreateSortedBeamInfo(Dictionary<string, int> sizeCounts) { List<BeamSizeInfo> beamInfoList = new List<BeamSizeInfo>(); const double concreteDensity = 25.0; // 混凝土容重 (kN/m³) foreach (var kvp in sizeCounts) { string size = kvp.Key; int count = kvp.Value; // 解析尺寸 string[] dimensions = size.Split('x'); if (dimensions.Length != 2) continue; if (!double.TryParse(dimensions[0], out double width)) continue; if (!double.TryParse(dimensions[1], out double height)) continue; // 计算截面面积 (mm² → m²) double area = (width * height) / 1_000_000.0; // 计算线荷载 double lineLoad = area * concreteDensity; beamInfoList.Add(new BeamSizeInfo { Size = size, Count = count, Width = width, Height = height, Area = area, LineLoad = lineLoad }); } // 按线荷载值降序排序(最大值排在最前) return beamInfoList.OrderByDescending(b => b.LineLoad).ToList(); } // 创建梁统计表格(添加备注行) private void CreateBeamStatisticsTable( Transaction tr, Database db, Point3d insertPoint, List<BeamSizeInfo> beamInfoList) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForWrite); // 创建表格对象 Table table = new Table(); table.Position = insertPoint; // 设置表格尺寸(行数 = 标题行 + 表头行 + 数据行 + 汇总行 + 备注行) int dataRows = beamInfoList.Count; table.SetSize(4 + dataRows, 5); // 5列,增加一行用于备注 table.SetRowHeight(8); // 行高 table.SetColumnWidth(15); // 列宽 // 设置表格样式 table.TableStyle = db.Tablestyle; table.Layer = "统计表"; table.ColorIndex = 0; // ByLayer // === 设置标题行 === table.Cells[0, 0].Value = "梁截面尺寸统计表(按线荷载排序)"; table.Cells[0, 0].Alignment = CellAlignment.MiddleCenter; table.MergeCells(CellRange.Create(table, 0, 0, 0, 4)); // 合并标题行 table.Rows[0].Height = 15; // 标题行高度 // === 设置表头行 === string[] headers = { "序号", "梁截面尺寸(mm)", "出现数量", "截面面积(㎡)", "梁线荷载(kN/m)" }; for (int col = 0; col < 5; col++) { table.Cells[1, col].Value = headers[col]; table.Cells[1, col].Alignment = CellAlignment.MiddleCenter; // 设置表头背景色 - 兼容旧版API Cell headerCell = table.Cells[1, col]; // 使用更兼容的方式设置背景色 headerCell.Color = Color.FromColorIndex(ColorMethod.ByAci, 5); // 蓝色背景 headerCell.TextHeight = 3.5; // 设置文字高度 } // === 填充数据行 === int rowIndex = 2; int sequence = 1; double totalArea = 0; double totalLoad = 0; // 按线荷载值降序排列(最大值排在最前) foreach (BeamSizeInfo info in beamInfoList) { // 填充表格数据 table.Cells[rowIndex, 0].Value = sequence.ToString(); // 序号 table.Cells[rowIndex, 1].Value = info.Size; // 尺寸 table.Cells[rowIndex, 2].Value = info.Count.ToString(); // 数量 table.Cells[rowIndex, 3].Value = info.Area.ToString("F4"); // 面积 table.Cells[rowIndex, 4].Value = info.LineLoad.ToString("F2"); // 荷载 // 设置荷载列文本颜色(兼容旧版API) Cell loadCell = table.Cells[rowIndex, 4]; if (info.LineLoad > 10) // 高荷载用红色 loadCell.Color = Color.FromColorIndex(ColorMethod.ByAci, 1); else if (info.LineLoad > 5) // 中等荷载用黄色 loadCell.Color = Color.FromColorIndex(ColorMethod.ByAci, 2); else // 低荷载用绿色 loadCell.Color = Color.FromColorIndex(ColorMethod.ByAci, 3); // 累计汇总值 totalArea += info.Area * info.Count; totalLoad += info.LineLoad * info.Count; sequence++; rowIndex++; } // === 添加汇总行 === int summaryRow = rowIndex; table.Cells[summaryRow, 0].Value = "汇总"; table.Cells[summaryRow, 0].Alignment = CellAlignment.MiddleCenter; table.MergeCells(CellRange.Create(table, summaryRow, 0, summaryRow, 1)); // 合并前两列 table.Cells[summaryRow, 2].Value = beamInfoList.Sum(b => b.Count).ToString(); table.Cells[summaryRow, 3].Value = totalArea.ToString("F4"); table.Cells[summaryRow, 4].Value = totalLoad.ToString("F2"); // 设置汇总行样式(兼容旧版API) for (int col = 0; col < 5; col++) { Cell cell = table.Cells[summaryRow, col]; cell.Color = Color.FromColorIndex(ColorMethod.ByAci, 1); // 红色文字 cell.TextHeight = 4.0; // 稍大的字体 } // === 添加备注行 === int remarkRow = summaryRow + 1; table.Cells[remarkRow, 0].Value = "备注:表中线荷载值仅做参考值。"; table.Cells[remarkRow, 0].Alignment = CellAlignment.MiddleLeft; // 合并整行作为备注 table.MergeCells(CellRange.Create(table, remarkRow, 0, remarkRow, 4)); // 设置备注行样式(兼容旧版API) Cell remarkCell = table.Cells[remarkRow, 0]; remarkCell.TextHeight = 6; // 设置较小的字体大小 remarkCell.Color = Color.FromColorIndex(ColorMethod.ByAci, 2); // 绿色文字 // 设置备注行高度(略低于其他行) table.Rows[remarkRow].Height = 6; // 添加表格到图形 btr.AppendEntity(table); tr.AddNewlyCreatedDBObject(table, true); } } 将以上四个功能代码重写一遍
最新发布
07-06
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值