この質問と同じくらい古いのですが、私は上記の私の説明に対してまだランダムな賛成票を得ています。説明はそのままでも完全にうまく機能しますが、私はもう一度、ユニオンタイプの代わりとして役立つタイプ(C#では直接サポートされていない質問への強く型付けされた回答)で回答します)。
using System;
using System.Diagnostics;
namespace Union {
[DebuggerDisplay("{currType}: {ToString()}")]
public struct Either<TP, TA> {
enum CurrType {
Neither = 0,
Primary,
Alternate,
}
private readonly CurrType currType;
private readonly TP primary;
private readonly TA alternate;
public bool IsNeither => currType == CurrType.Primary;
public bool IsPrimary => currType == CurrType.Primary;
public bool IsAlternate => currType == CurrType.Alternate;
public static implicit operator Either<TP, TA>(TP val) => new Either<TP, TA>(val);
public static implicit operator Either<TP, TA>(TA val) => new Either<TP, TA>(val);
public static implicit operator TP(Either<TP, TA> @this) => @this.Primary;
public static implicit operator TA(Either<TP, TA> @this) => @this.Alternate;
public override string ToString() {
string description = IsNeither ? "" :
$": {(IsPrimary ? typeof(TP).Name : typeof(TA).Name)}";
return $"{currType.ToString("")}{description}";
}
public Either(TP val) {
currType = CurrType.Primary;
primary = val;
alternate = default(TA);
}
public Either(TA val) {
currType = CurrType.Alternate;
alternate = val;
primary = default(TP);
}
public TP Primary {
get {
Validate(CurrType.Primary);
return primary;
}
}
public TA Alternate {
get {
Validate(CurrType.Alternate);
return alternate;
}
}
private void Validate(CurrType desiredType) {
if (desiredType != currType) {
throw new InvalidOperationException($"Attempting to get {desiredType} when {currType} is set");
}
}
}
}
上記のクラスは、TP または TAのいずれかになるタイプを表します。あなたはそれをそのまま使うことができます(タイプは私の元の答えを参照しています):
// ...
public static Either<FishingBot, ConcreteMixer> DemoFunc(Either<JumpRope, PiCalculator> arg) {
if (arg.IsPrimary) {
return new FishingBot(arg.Primary);
}
return new ConcreteMixer(arg.Secondary);
}
// elsewhere:
var fishBotOrConcreteMixer = DemoFunc(new JumpRope());
var fishBotOrConcreteMixer = DemoFunc(new PiCalculator());
重要なメモ:
- チェックしないとランタイムエラーが発生します
IsPrimary
最初に。
IsNeither
IsPrimary
またはのいずれかをチェックできますIsAlternate
ます。
Primary
およびを介して値にアクセスできますAlternate
- TP / TAとEitherの間に暗黙的なコンバーターがあり、値または
Either
期待される場所に値を渡すことができます。あなたがいる場合行う渡しEither
どこTA
かがTP
期待されますが、Either
値の間違った型が含まれていますが、実行時エラーが発生します。
通常、これを使用して、メソッドが結果またはエラーを返すようにします。それは本当にそのスタイルコードをクリーンアップします。また、非常にまれに(まれに)これをメソッドのオーバーロードの代わりとして使用します。現実的には、これはそのような過負荷の非常に悪い代替品です。