Hacktoberfest 2026:維護者為十月標記出來的 issue,仍然開放、適合新手。 瀏覽 Hacktoberfest issue

How can I assign TypeConverter to Enum in `Options`?

未關閉
#944 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
3/5
預估耗時
1-2 天
新手友好度
35/100
Issue 類型
缺陷
描述清晰度
基本清楚
活躍度
停滯
技術堆疊
csharp
領域
cli

研究方向

從 Options.Operation 屬性和 TypeDescriptor.AddAttributes 呼叫開始,接著追蹤命令列剖析器的轉換路徑,以判定使用的是屬性層級還是 enum 層級的轉換器。完成的定義是記錄或修正支援的註冊路徑,讓自訂轉換器將 cd 對應至 Operation.CreateDirectory。

由索引模型根據 Issue 內容生成。

描述

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?

主要語言
C#
星號
4.8k
分支
478
PR 合併指標
30 天內沒有已合併 PR

貢獻指南

這個儲存庫沒有索引到貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

commandlineparser/commandline 的其他 Issue

查看 commandlineparser/commandline 的全部 Issue

相似的 Issue

更多 C# Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。