Last active
December 31, 2015 18:09
-
-
Save issacg/8024973 to your computer and use it in GitHub Desktop.
Override ToString() to allow a custom arguments class created for the CommandLine C# library (http://github.com/gsscoder/commandline) to "reverse" itself back into an argument string. Based on code written at https://github.com/gsscoder/commandline/issues/114 by @issacg and modified to be LINQ-based by @allonhadaya
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using CommandLine; | |
class MyArguments { | |
// Add some [Option]s here for CommandLine to use | |
public override string ToString() | |
{ | |
return string.Concat(this | |
.GetType() | |
.GetProperties() | |
.Where(p => Attribute.IsDefined(p, typeof(OptionAttribute))) | |
// for all properties with option attributes | |
.SelectMany(p => p | |
.GetCustomAttributes(typeof(OptionAttribute), inherit: true) | |
.Select(a => (OptionAttribute)a) | |
// get the type, name, and data | |
.Select(a => new { | |
type = p.GetType(), | |
name = a.LongName, | |
data = p.GetValue(this, null) | |
}) | |
// where data is not default | |
.Where(v => v.data != ((v.type.IsValueType) ? Activator.CreateInstance(v.type) : null)) | |
// make an argument string | |
.Select(v => string.Format("--{0} {1} ", v.name, v.data)))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment