commandlineparser / commandlineparser/commandline

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

未關閉
#944 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視
主要語言
C#
星號
4.8k
分支
478
PR 合併指標
30 天內沒有已合併 PR

描述

I've declared `Options` which will be used for parsing command line.
```csharp
public class Options {
// ...
[Option('o', "operation", HelpText = "")]
[TypeConverter(typeof(OperationConverter))]
public Operation Operation { get; set; }
}
```
And the `Operation` looks like this:
```csharp
[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`
```csharp
public class OperationConverter : EnumConverter {
// ... candidates for other enum values
private static readonly List 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](https://github.com/commandlineparser/commandline/issues/83#issuecomment-671916065) 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`](https://github.com/commandlineparser/commandline/wiki/T_CommandLine_Core_TypeDescriptor). [this](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.typedescriptor?view=netframework-4.8.1#methods) has `.AddAttributes()`, but this doesn't seem to work.
```csharp
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?

貢獻指南

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

研究方向

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

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

評估

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

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

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