commandlineparser / commandlineparser/commandline

C#8 Support for Default Interface in Options

オープン
#696 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る
主要言語
C#
スター
4.8k
フォーク
478
PR マージ指標
30日以内にマージされた PR はありません

説明

I have a lot of projects reusing the same kind of option. So far I've been using inheritance to achieve some kind of code reuse but it's not perfect and quickly becomes unwieldy.

Since C# 8 supports default interfaces I tried the following (I know a lot of people are horrified by default interfaces but since we can't inherit from more than one abstract class I don't see any other way to implement what I'm looking for (which would be kind of like traits in other languages). If there's another way to do this please let me know.

Let's say we have this StringOptionOne (with a lot of other StringOptions like StringOptionTwo, StringOptionThree, StringOptionFour and we want to be able to use them to compose the Options class.

```
public class Options
{
[Option('s', "stringoptionone", Required = true, HelpText = "The string option one value.")]
public string StringOptionOne { get; set; }
}
```

Defining a regular interface I still have to implement the property and the attributes in each Options and I'm trying to avoid this.

Using inheritance it's impossible to have all the possible variants since we can't inherit from more than one class.

But using Default interface we could have something like this:

```
public interface IDefaultStringOptionOne
{
private static string _stringOptionOne = "";

[Option('s', "stringoptionone", Required = true, HelpText = "The string option one value.")]
public static string StringOption
{
get => _stringOptionOne;
set => _stringOptionOne = value;
}
}
```

And use it like this:

```
public class Options: IDefaultStringOptionOne, IDefaultStringOptionTwo
{
}
```

With C#8 this compiles but I'm getting a null when parsing the option.

Is there a way to support this...? Or another way to compose Options at the property level...?

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。