Revit二开–常用方法封装
在唐僧课堂(http://bimdp.ke.qq.com) 常用的封装方法。
很多工程专业转Revit二次开发的朋友,对一些重复使用的方法通常采用粘贴复制的做法,这样做很浪费时间。其实在C#编程语言中有丰富的方法来实现我们重用代码的目的,而不必使用粘贴复制的方式。以下举简单的两个例子。
1.封装元素获取的方法
public static class Extensions
{
public static Element GetElement(this ElementID id,Document doc)
{
return doc.GetElement(id);
}
public static Element GetElement(this Reference ref1,Document doc)
{
return doc.GetElement(Ref1.Id);
}
}
采用这个扩展方法可以快速的使用elementId 获取 所对应的元素 ,可以在一行代码中完成选取元素操作 具体使用方法如下:
[Transaction(TransactionMode.Manual)]
public class TestCmd:IExternalCommand
{
public Result Execute(ExternalCommandData commandData,ref string message,ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.AitiveUIDocument;
Document doc = uidoc.Document;
var sel = uidoc.Selection;
//在一行代码中完成元素的选择
Element element = sel.PiclObject(ObjectType.Element).GetElement(doc);
//当然如果是要选取的元素 是 墙 或者别的 只需要 用 as 转换一下即可 如下:
Wall wall = sel.PickObject(ObjectType.Element).GetElement(doc) as Wall;
}
}
2.过滤器封装 ISelecttionFilter
通常情况下我们在用鼠标选择元素的时候,会有一个过滤器类,来筛选目标元素,使符合条件的元素可以被选中,而每种情况都要单独建立一个类来继承ISelectionFilter接口,这样做起来十分繁琐。因此我们将ISelectionFilter这个接口封装到类中,每次重复调用。
好的,上代码
//过滤器封装
public static class FilterHelper
{
public static MultiSelectionFilter GetSelectionFilter(this Document doc, Func<Element, bool> func1, Func<Reference, bool> func2 = null)
{
return new MultiSelectionFilter(func1, func2);
}
}
public class MultiSelectionFilter : ISelectionFilter
{
private Func<Element, bool> eleFunc;
private Func<Reference, bool> refFunc;
public MultiSelectionFilter(Func<Element, bool> func, Func<Reference, bool> func1)
{
eleFunc = func;
refFunc = func1;
}
public bool AllowElement(Element elem)
{
return refFunc != null ? true : eleFunc(elem);
}
public bool AllowReference(Reference reference, XYZ position)
{
return refFunc == null ? false : refFunc(reference);
//return refFunc(reference);
}
}
使用方法如下
[Transaction(TransactionMode.Manual)]
public class TestCmd:IExternalCommand
{
public Result Execute(ExternalCommandData commandData,ref string message,ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.AitiveUIDocument;
Document doc = uidoc.Document;
var sel = uidoc.Selection;
//以下代码仅能选择墙这一类元素
var elerefs = sel.PiclObjects(ObjectType.Element,doc.GetSelectionFilter(m=>m is Wall));
}
}
版权声明:本文为binbinstrong原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。