C# 中的辨別聯合
問題:
問題:如何創建如何創建聯合辨別(又稱tagged union)?此聯合允許使用不同的類型表示單一值,並提供編譯時類型安全性。
答案:public abstract class Union3<A, B, C> { public abstract T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h); private Union3() { } public sealed class Case1 : Union3<A, B, C> { public readonly A Item; public Case1(A item) : base() { this.Item = item; } public override T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h) { return f(Item); } } public sealed class Case2 : Union3<A, B, C> { public readonly B Item; public Case2(B item) { this.Item = item; } public override T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h) { return g(Item); } } public sealed class Case3 : Union3<A, B, C> { public readonly C Item; public Case3(C item) { this.Item = item; } public override T Match<T>(Func<A, T> f, Func<B, T> g, Func<C, T> h) { return h(Item); } } }
Union3<int, char, string> union1 = Union3<int, char, string>.Case1(5); Union3<int, char, string> union2 = Union3<int, char, string>.Case2('x'); Union3<int, char, string> union3 = Union3<int, char, string>.Case3("Juliet");
string value1 = union1.Match(num => num.ToString(), character => new string(new char[] { character }), word => word); string value2 = union2.Match(num => num.ToString(), character => new string(new char[] { character }), word => word); string value3 = union3.Match(num => num.ToString(), character => new string(new char[] { character }), word => word);
以上是如何在 C# 中建立類型安全的可區分聯合(標記聯合)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!