C# CreateEmployee()函數(shù)
C#語言有很多值得學習的地方,這里我們主要介紹C# CreateEmployee()函數(shù),包括介紹 測試C# CreateEmployee()函數(shù)。加入一個Test命令來測試CreateEmployee等方面。
修改C# CreateEmployee()函數(shù)以重用
1)讓我們來修改C# CreateEmployee()函數(shù),以讓它可以接收名字、薪水、部門和職位并返回創(chuàng)建的雇員塊索引的ObjectId。函數(shù)的形式如下(你可以改變參數(shù)順序)
- public ObjectId CreateEmployee
(string name, string division, double salary, Point3d pos)
2) 移除上面函數(shù)中的CommandMethod屬性”CREATE”,這樣它就不再是用來創(chuàng)建雇員的命令。
3) 修改函數(shù)的代碼,這樣就可以正確地設置塊索引的名字、職位、部門和薪水和它的擴展字典。
- //替換
- BlockReference br = new BlockReference
(new Point3d(10, 10, 0), CreateEmployeeDefinition());- //為
- BlockReference br = new BlockReference
(pos, CreateEmployeeDefinition());
- //替換
- xRec.Data = new ResultBuffer(
- new TypedValue((int)DxfCode.Text, "Earnest Shackleton"),
- new TypedValue((int)DxfCode.Real, 72000),
- new TypedValue((int)DxfCode.Text, "Sales"));
- //為
- xRec.Data = new ResultBuffer(
- new TypedValue((int)DxfCode.Text, name),
- new TypedValue((int)DxfCode.Real, salary),
- new TypedValue((int)DxfCode.Text, division));
4) 因為我們把雇員的名字從MText替換成塊的屬性定義,因此我們要創(chuàng)建一個相應的屬性索引來顯示雇員的名字。屬性索引將使用屬性定義的屬性。
- //替換:
- btr.AppendEntity(br);//加入索引到模型空間
- trans.AddNewlyCreatedDBObject(br,true);//讓事務處理知道
- //為
- AttributeReferenceattRef=newAttributeReference();
- //遍歷雇員塊來查找屬性定義
- BlockTableRecordempBtr=(BlockTableRecord)trans.
GetObject(bt["EmployeeBlock"],OpenMode.ForRead);- foreach(ObjectIdidinempBtr)
- {
- Entityent=(Entity)trans.GetObject(id,OpenMode.ForRead,false);
- //打開當前的對象!
- if(entisAttributeDefinition)
- {
- //設置屬性為屬性索引中的屬性定義
- AttributeDefinitionattDef=((AttributeDefinition)(ent));
- attRef.SetPropertiesFrom(attDef);
- attRef.Position=newPoint3d(attDef.Position.X+br.Position.X,
attDef.Position.Y+br.Position.Y,attDef.Position.Z+br.Position.Z);- attRef.Height=attDef.Height;
- attRef.Rotation=attDef.Rotation;
- attRef.Tag=attDef.Tag;
- attRef.TextString=name;
- }
- }
- //把索引加入模型空間
- btr.AppendEntity(br);
- //把屬性索引加入到塊索引
- br.AttributeCollection.AppendAttribute(attRef);
- //讓事務處理知道
- trans.AddNewlyCreatedDBObject(attRef,true);
- trans.AddNewlyCreatedDBObject(br,true);
5)不要忘記返回雇員塊索引的ObjectId,但要在提交事務處理之后才能返回:
- trans.Commit();
- return br.ObjectId;
6) 測試C# CreateEmployee()函數(shù)。加入一個Test命令來測試CreateEmployee:
- [CommandMethod("Test")]
- public void Test()
- {
- CreateEmployee("Earnest Shackleton", "Sales", 10000, new Point3d(10, 10, 0));
- }
【編輯推薦】