使用 C# 9.0 记录构建类似智能枚举/类似歧视联合/类似总和类型的数据结构?

use*_*861 5 oop enums discriminated-union c#-9.0 record-classes

record在 C# 中使用类型,看起来构建类似可区分联合的数据结构可能非常有用,我只是想知道我是否遗漏了一些我以后会后悔的问题。例如:

abstract record CardType{
    // Case types
    public record MaleCardType(int age) : CardType{}
    public record FemaleCardType : CardType{}

    // Api
    public static MaleCardType Male(int age) => new MaleCardType(age);
    public static FemaleCardType Female => new FemaleCardType();
}

var w = CardType.Male(42);
var x = CardType.Male(42);
var y = CardType.Male(43);
var z = CardType.Female;
Assert.Equal<CardType>(w,x); //true
Assert.Equal<CardType>(x,y); //false
Assert.Equal<CardType>(y,z); //false
Run Code Online (Sandbox Code Playgroud)

这似乎比用单例和相等比较器等构建抽象类简单得多,但我是否缺少一些我不想这样做的原因?

Kei*_*las 14

It's a great way to go, I've been playing around with it, for instance, on https://fsharpforfunandprofit.com/posts/designing-for-correctness/ which has some examples of C# code, some F# code that uses types and discriminated unions, and then some modified (but still terrible C# code). So I rewrite the C# using C# 9s records and the same way of doing DUs

Sample code, which is a tiny bit uglier than the F#, but still quite concise and has the advantages of the F# code .

using System;
using System.Collections.Immutable;

namespace ConsoleDU
{
    record CartItem(string Value);

    record Payment(decimal Amount);

    abstract record Cart
    {
        public record Empty () : Cart
        {
            public new static Active Add(CartItem item) => new(ImmutableList.Create(item));
        }
        public record Active (ImmutableList<CartItem> UnpaidItems) : Cart
        {
            public new Active Add(CartItem item) => this with {UnpaidItems = UnpaidItems.Add(item)};
            public new Cart Remove(CartItem item) => this with {UnpaidItems = UnpaidItems.Remove(item)} switch
            {
                var (items) when items.IsEmpty => new Empty(),
                { } active => active
            };

            public new Cart Pay(decimal amount) => new PaidFor(UnpaidItems, new(amount));
        }
        public record PaidFor (ImmutableList<CartItem> PaidItems, Payment Payment) : Cart;

        public Cart Display()
        {
            Console.WriteLine(this switch
            {
                Empty => "Cart is Empty",
                Active cart => $"Cart has {cart.UnpaidItems.Count} items",
                PaidFor(var items, var payment) => $"Cart has {items.Count} paid items. Amount paid: {payment.Amount}",
                _ => "Unknown"
            });
            return this;
        }

        public Cart Add(CartItem item) => this switch
        {
            Empty => Empty.Add(item),
            Active state => state.Add(item),
            _ => this
        };

        public static Cart NewCart => new Empty();

        public Cart Remove(CartItem item) => this switch
        {
            Active state => state.Remove(item),
            _ => this
        };

        public Cart Pay(decimal amount) => this switch
        {
            Active cart => cart.Pay(amount),
            _ => this
        };
    }

    class Program
    {
        static void Main(string[] args)
        {
            Cart.NewCart
                .Display()
                .Add(new("apple"))
                .Add(new("orange"))
                .Display()
                .Remove(new("orange"))
                .Display()
                .Remove(new("apple"))
                .Display()
                .Add(new("orange"))
                .Pay(23M)
                .Display();
            ;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ssh*_*ack 7

record PaymentType{
    public record CreditCard(CardNumber CardNumber, SecurityCode CVV, Expiration ExpirationDate, NameOnCard Name) : PaymentType();
    public record ACH(AccountNumber AccountNumber, RoutingNumber RoutingNumber) : PaymentType();
    public record Paypal(IntentToken Token) : PaymentType();

    private PaymentType(){} // private constructor can prevent derived cases from being defined elsewhere
}

public void HandlePayment(PaymentType paymentInfo){
    paymentInfo switch {
        CreditCard cardInfo => //...
        ACH checkInfo => //...
        Paypal paypalInfo => //...
    };
}
Run Code Online (Sandbox Code Playgroud)

链接到源文章