Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

How can I assign TypeConverter to Enum in Options? #944

Copy link
Copy link
@TetraTheta

Description

@TetraTheta
Issue body actions

I've declared Options which will be used for parsing command line.

public class Options {
  // ...
  [Option('o', "operation", HelpText = "")]
  [TypeConverter(typeof(OperationConverter))]
  public Operation Operation { get; set; }
}

And the Operation looks like this:

[TypeConverter(typeof(OperationConverter))]
public enum Operation {
  // ...
  CreateDirectory,
  // ...
}

Since CreateDirectory is quite long to type in command line, I want to allow cd as valid Operation.CreateDirectory

public class OperationConverter : EnumConverter {
  // ... candidates for other enum values
  private static readonly List<string> OperationCandidate = ["createdirectory", "cd"];

  // ...
  public override object ConvertFrom(ITypeDescriptorContext? ctx, CultureInfo? ci, object value) {
    if (value is string s) {
      string l = s.Trim().ToLowerInvariant();
      // ...
      if (OperationCandidate.Contains(l)) return Operation.CreateDirectory;
      // ...
    }
  }
}

But I can't assign this OperationConverter to Options.Operation. I don't see anything that might be related to this.

#83 says it is resolved, but at the bottom of that issue, someone said:

I dont think this works in the latest version. I tried annotating my option's property, but the converter is not invoked. Instead I had to register it using TypeDescriptor.AddAttributes().

But I don't see any methods named .AddAttributes() in TypeDescriptor. this has .AddAttributes(), but this doesn't seem to work.

  private static void Main(string[] args) {
    // ...
    TypeDescriptor.AddAttributes(typeof(Operation), new TypeConverterAttribute(typeof(OperationConverter)));
    // other logic + command line parsing
  }

Now I'm completely lost. Wiki doesn't provide any useful information that I can easily access.

How can I assign TypeConverter to Enum in Options?

Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.