/// <summary> /// Creates an argument of a specific type by parsing the string /// </summary> /// <returns>The parsed object.</returns> /// <param name="value">The string to parse.</param> /// <param name="targettype">The type to parse to.</param> public static object ArgumentFromString(string value, Type targettype) { if (targettype.IsEnum) { var entries = ExpandEnvironmentVariables(value ?? "") .Split('|') .Select(x => Enum.Parse(targettype, x, true)) .ToArray(); if (entries.Length == 1) { return(entries.First()); } else { return(Enum.ToObject( targettype, entries.Select(x => (int)Convert.ChangeType(x, typeof(int))).Sum() )); } } if (targettype.IsArray) { // TODO: Handle embedded comma values in strings? var args = (value ?? "") .Split(',') .Select(x => ArgumentFromString((x ?? string.Empty).Trim(), targettype.GetElementType())) .ToArray(); // Manually convert to the right type var res = Array.CreateInstance(targettype.GetElementType(), args.Length); Array.Copy(args, res, args.Length); return(res); } if ((targettype.IsArray || targettype == typeof(string)) && string.Equals(value, "null", StringComparison.OrdinalIgnoreCase)) { return(null); } if (targettype == typeof(TimeSpan)) { return(ParseUtil.ParseDuration(ExpandEnvironmentVariables(value))); } if (targettype == typeof(int) || targettype == typeof(uint) || targettype == typeof(long) || targettype == typeof(ulong)) { return(Convert.ChangeType(ParseUtil.ParseSize(ExpandEnvironmentVariables(value)), targettype)); } if (targettype == typeof(bool)) { return(ParseUtil.ParseBool(ExpandEnvironmentVariables(value))); } return(Convert.ChangeType(ExpandEnvironmentVariables(value), targettype)); }