问题描述
我是新手。假设这些都代表C#中的不同类:
- ContactDetails
- 互联网
- 电话号码
- 地址
如何在F#中创建一个“列表”以容纳不同的具体类型?
- 名称-字符串
WFP / XAML将使用此“列表”类型。
(我认为需要使用F#列表的接口,但我不知道它是如何实现的-F#对我来说真的很新。:
TIA
解决方法
考虑使用Seq代替List来帮助C#客户端:
我建议使用序列(即seq)而不是C#消耗列表。 因此,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
]
,
对不起,这是您想要的吗?
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");
}
}
}
}