C#/ WPFで使用するインターフェイスからF#リストを作成する方法

Aug 20 2020

私は初心者です。これらのそれぞれがC#の異なるクラスを表すとすると:

  1. ContactDetails
  2. インターネット
  3. 電話番号
  4. 住所

さまざまな具象タイプを保持するために、F#で「リスト」をどのように作成しますか?

上記のすべてのタイプには、次の共通フィールドがあります。

  1. 名前-文字列

名前以外では、すべての具象タイプのフィールドと内容が異なります。

この「リスト」タイプは、WFP / XAMLによって使用されます。

(F#リストのインターフェイスを使用する必要があると思いますが、これがどのように実装されているかわかりません。F#は私にとって本当に新しいものです。:)

TIA

回答

3 ScottNimrod Aug 20 2020 at 19:03

C#クライアントを支援するために、Listの代わりにSeqを使用することを検討してください。

C#の消費には、リストの代わりにシーケンス(つまり、seq)を使用することをお勧めします。したがって、F#のシーケンスはC#のIEnumerableと同等です。したがって、Windowsアプリからこれらのアイテムを使用できるようになります。

要件を実装する方法は次のとおりです。

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

すみません、これはあなたが望むものですか?

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");
            }
        }
    }
}