protected virtual bool ShouldAppendFlag(Argument argument, Type type, object value) { if (CommonSerializationChecker != null && !CommonSerializationChecker(argument, type, value)) { return(false); } if (SerializationCheckers.TryGetValue(type, out Func <Argument, Type, object, bool> append)) { return(append(argument, type, value)); } return(true); }
/// <summary> /// Sets this <see cref="CommandLineBuilder"/> to its default settings. /// </summary> public virtual void SetDefaults() { ValueTranslators.Clear(); Builders.Clear(); SerializationCheckers.Clear(); ArgumentSeperator = " "; Seperator = " "; // Only serialize flag if value isn't null. This is called before any other registered serialization checkers. CommonSerializationChecker = (a, t, v) => v != null; // Only serialize boolean flags if the value is true. SerializationCheckers.Add(typeof(bool), (a, t, v) => (bool)v); // Serialize boolean flags if value isn't false. // Only serialize dictionaries if they contain items. SerializationCheckers.Add(typeof(Dictionary <string, string>), (a, t, v) => ((Dictionary <string, string>)v).Count > 0); // Translates string properties to string... duh! ValueTranslators.Add(typeof(string), (a, t, v) => v.ToString()); // Translate DateTime objects to the format of "yyyyMMdd". ValueTranslators.Add(typeof(DateTime), (a, t, v) => ((DateTime)v).ToString("yyyyMMdd")); // Translates enum properties to string by using the name representing the enum value. ValueTranslators.Add(typeof(Enum), (a, t, v) => { string name = Enum.GetName(t, v); switch (a.EnumCase) { case EnumCasePolicy.Lowercase: return(name.ToLower()); case EnumCasePolicy.Uppercase: return(name.ToUpper()); case EnumCasePolicy.Default: default: return(name); } }); // Custom builder for string -> string dictionaries repeatedly adds flag with key-value pair seperated by colon. Builders.Add(typeof(Dictionary <string, string>), (argument, type, value) => { Dictionary <string, string> dictionary = (Dictionary <string, string>)value; if (dictionary.Count == 0) { return(null); // Returning null for a builder, or value translator ignores this argument. } StringBuilder sb = new StringBuilder(); foreach (KeyValuePair <string, string> entry in dictionary) { sb.Append(BuildFlag(argument, string.Format("{0}:{1}", entry.Key, entry.Value))).Append(ArgumentSeperator); } if (dictionary.Count > 1) { sb.Remove(sb.Length - ArgumentSeperator.Length, ArgumentSeperator.Length); } return(sb.ToString()); }); }