简体   繁体   中英

How to pass a discriminated union from C# to a F# function (F# - C# interop)

Definition of the model:

type ItemEvent =
| ItemCreated of ItemCreated
and ItemCreated = { timestamp:DateTime; id:ItemId; name:string; description:string option } interface IEvent

Here is the interface with the method that I want to call:

type IItemWriteAccess =
    abstract Update: ItemEvent -> Result<unit, DomainMessage>

Here is the C# code:

public class ItemEventHandlers
{
    private readonly IItemWriteAccess _repository;

    public ItemEventHandlers(IItemWriteAccess repository)
    {
        _repository = repository;
    }

    public void Handle(ItemCreated msg)
    {
        if(msg == null) throw new ArgumentNullException("msg");

        _repository.Update(msg); // this doesn't work
    }
}

This produces the following error message:

Argument 1: cannot convert from 'DomainModels.ItemCreated' to 'DomainModels.ItemEvent'

Upcasting to ItemEvent also doesn't work.

How can I resolve this?

Since Update takes an ItemEvent , an ItemCreated instance cannot be passed as an argument.

I have to create an ItemEvent and pass the ItemCreated instance to the constructor function like this:

var @event = ItemEvent.NewItemCreated(msg);

Then I can pass it to Update :

public void Handle(ItemCreated msg)
{
    if(msg == null) throw new ArgumentNullException("msg");

    var @event = ItemEvent.NewItemCreated(msg);
    _repository.Update(@event);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM