Come creare un elenco F# da un'interfaccia che deve essere utilizzato da C#/WPF

Aug 20 2020

Sono un principiante. Dato che ognuno di questi rappresenta classi diverse in C#:

  1. Dettagli del contatto
  2. Internet
  3. Numeri di telefono
  4. Indirizzi

Come viene creato un "elenco" in F# per contenere i diversi tipi concreti?

Tutti i tipi di cui sopra avranno un campo comune di:

  1. Nome -- stringa

Al di fuori del nome, tutti i tipi concreti avranno campi e contenuti diversi.

Questo tipo di "elenco" deve essere utilizzato da WFP/XAML.

(Penso che sia necessario utilizzare un'interfaccia per l'elenco F #, ma non so come sia implementata - F # è davvero una novità per me. :)

TIA

Risposte

3 ScottNimrod Aug 20 2020 at 19:03

Prendi in considerazione l'utilizzo di Seq invece di List per aiutare i client C#:

Consiglierei di utilizzare una sequenza (ad esempio seq) anziché un elenco per il consumo di C#. Quindi una sequenza in F# equivale a IEnumerable in C#. Pertanto, sarai in grado di utilizzare questi elementi dalla tua app di Windows.

Ecco come implementerei il requisito:

type ContactDetail = { Name : string; Other:string }
type Internet      = { Name : string; Other:string }
type PhoneNumber   = { Name : string; Other:string }
type Address       = { Name : string; Other:string }

type MyType =
    | ContactDetails of ContactDetail seq
    | Internet       of Internet      seq
    | PhoneNumbers   of PhoneNumber   seq
    | Addresses      of Address       seq

let contactDetail  : ContactDetail = { Name="some name"; Other="???" }
let contactDetails = ContactDetails [contactDetail]

let internet       : Internet = { Name="some name"; Other="???" }
let internets      = Internet [internet]

let phoneNumber    : PhoneNumber = { Name="some name"; Other="???" }
let PhoneNumbers   = PhoneNumbers [phoneNumber]

let myTypes : MyType seq = seq [ contactDetails
                                 internets
                                 PhoneNumbers
                               ]
2 AnibalYeh Aug 20 2020 at 09:33

Scusami, è questo che vuoi?

F#

module FSharpTest.ListTest
open System


type YourType = Object

type ContactDetails = YourType
type Internet = YourType
type PhoneNumbers = YourType
type Addresses = YourType


type WrapperOfCSharpClass =
| CD of ContactDetails
| I of Internet
| PN of PhoneNumbers
| A of Addresses

let list = [
    Unchecked.defaultof<WrapperOfCSharpClass>
    CD (new ContactDetails())
    I (new Internet())
]

C#

using System;
using FSharpTest;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var fsharplist_item = ListTest.list[0];
            if (fsharplist_item.IsPN)
            {
                Console.WriteLine("I am a phone number");
            } else if (fsharplist_item.IsA)
            {
                Console.WriteLine("I am an address");
            }
        }
    }
}