When reading the book “Functional Programming in C#”, I saw the concept of HOF. I felt that this method could be used to organize an extension method in the daily development process to achieve rapid calling of the program.

  1. Transaction function inherits from IDisposable
  2. We usually need to use using internal to operate Revit during development. Achieve automatic disassembly
  3. We need to create a generic function MTransaction and constrain it to the IDisposable interface
  4. Implement using keyword inside the above function to reduce repeated calls inside other functions, reduce code volume and reduce coupling
  5. Create function TransactionHelper to encapsulate this reference, and call the intermediate function through third-party call to complete the call

Function Structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static class MTransaction
{
public static void Using<TDisp>(TDisp disposable, Action<TDisp> f) where TDisp : IDisposable
{
using (disposable)
{
f(disposable);
}
}
}

public static class TransactionHelper
{
public static void Execute(Document doc, Action<IDisposable> f)
=> MTransaction.Using(new Transaction(doc, "create"), trans =>
{
trans.Start();
f(trans);
trans.Commit();
});
}

Call this method

1
2
3
4
5
TransactionHelper.Execute(doc, c =>
{
var line = Line.CreateBound(new XYZ(0, 0, 0), new XYZ(2000 / 304.8, 2000 / 304.8, 0));
Wall w = Wall.Create(doc, line, new ElementId(311), false);
});