By Augusto Goncalves (@augustomaia)
One of my favorites features of .NET is the ability to use Reflection. This is particularly powerful when we need to find something on the API that we’re not completely sure.
In this case we want to get all layers used on GetDisplay methods for some objects, let’s say AlignmentStyle. This specific case has GetDisplayStyleModel, GetDisplayStylePlan and GetDisplayStyleSection, but all options start with GetDisplay. Interesting!
So using Reflection let enumerate all methods that start with this prefix, then invoke them for all possible parameters. We assume the parameters are values from a enumeration, which can be found by Reflection.
Updates (January, 2016): Jeff improved the code to support some other types. See new version below.
public static List<string> GetDisplayStylesLayer(StyleBase style){ List<string> layers = new List<string>(); // get all methods that contains "DisplayStyle" on their names var methods = style.GetType().GetMethods() .Where(m => (m.Name.Contains("DisplayStyle") && !m.Name.Contains("_"))); // run through the collection of methods foreach (MethodInfo method in methods) { var methodparams = method.GetParameters(); if (methodparams.Length > 1) continue; // if more than 1, then we don't know if (methodparams.Length == 0) { DisplayStyle dispStyle = method.Invoke(style, new object[] { }) as DisplayStyle; if (dispStyle == null) continue; layers.Add(dispStyle.Layer); continue; } ParameterInfo param = methodparams[0]; if (!param.ParameterType.IsEnum) continue; // not a enum, skip // check all values on the enum foreach (var enumValue in Enum.GetValues( param.ParameterType)) { try { DisplayStyle dispStyle = method.Invoke(style, new object[] { enumValue }) as DisplayStyle; if (dispStyle == null || enumValue. ToString().Contains("Curvature")) continue;// something went wrong layers.Add(dispStyle.Layer); } catch { }
} } return layers;}
To use it, simply call the Extension method, below is a quick example:
[CommandMethod("getLayersFromDisplayStyle")]public static void CmdGetLayers(){ CivilDocument civilDoc = CivilApplication.ActiveDocument; using (Transaction trans = Application.DocumentManager .MdiActiveDocument.Database.TransactionManager .StartTransaction()) { StyleBase st = trans.GetObject( civilDoc.Styles.AlignmentStyles[0], OpenMode.ForRead) as StyleBase; List<string> res = st.GetDisplayStyleLayer(); foreach (string s in res) Application.DocumentManager.MdiActiveDocument .Editor.WriteMessage("n{0}", s); }}


Leave a Reply to Brian ChapmanCancel reply