扁平地图歧视工会
本文关键字:歧视 地图 | 更新日期: 2023-09-27 18:06:15
我正在使用Github上的一个名为OneOf的库。
基本上你有一种类型可以是许多类型中的一种,但是以一种静态安全的方式。
下面是我想要实现的一个例子。
我有A<T1, T2, T3, T4>
型和B<T1, T2, T3>
型,我想将B型"flapmap"转换为A型。因为A型可以接受来自B的任何一个T,这应该是可能的。
编译器强迫我在赋值给A之前从B中提取每个T,正如你可以看到下面愚蠢的x => x
lambdas。
我也不想以A<B<T1, T2, T3>, T4>
那样的结尾。
有人能想到这些OneOf类型的SelectMany吗?
using OneOf;
using System;
using System.IO;
namespace ScratchPad
{
class Program
{
struct BadRequest { }
struct Error { }
struct NotFound { }
static void Main(string[] arg)
{
string result = GetFile(@"c:'data'foo.txt").Match(
text => text,
badRequest => "filepath cannot be null",
notFound => "filepath does not exist",
error => "an error occurred"
);
Console.WriteLine(result);
}
static OneOf<string, BadRequest, NotFound, Error> GetFile(string filepath)
{
OneOf<string, BadRequest, NotFound, Error> response = new BadRequest();
if (filepath != null)
{
// How can I make the type from ReadText() automatically convert to the type of the response local variable, without having to write these silly lambda?
response = ReadText(filepath).Match<OneOf<string, BadRequest, NotFound, Error>>(x => x, x => x, x => x);
}
return response;
}
static OneOf<string, NotFound, Error> ReadText(string filepath)
{
OneOf<string, NotFound, Error> response = new NotFound();
try
{
if (File.Exists(filepath))
{
response = File.ReadAllText(filepath);
}
}
catch
{
response = new Error();
}
return response;
}
}
}
扩展方法可以是一种方法。
一个例子,我刚想到的,转换3到4个类型:
public static class OneOfExtensions
{
public static OneOf<T1, T2, T3, T4> ConvertOneOf<T1, T2, T3, T4>(this OneOf<T1, T2, T3> oneOf)
{
return oneOf.Match<OneOf<T1, T2, T3, T4>>(x => x, x => x, x=> x);
}
public static OneOf<T1, T2, T3, T4> ConvertOneOf<T1, T2, T3, T4>(this OneOf<T1, T2, T4> oneOf)
{
return oneOf.Match<OneOf<T1, T2, T3, T4>>(x => x, x => x, x=> x);
}
public static OneOf<T1, T2, T3, T4> ConvertOneOf<T1, T2, T3, T4>(this OneOf<T1, T3, T4> oneOf)
{
return oneOf.Match<OneOf<T1, T2, T3, T4>>(x => x, x => x, x=> x);
}
public static OneOf<T1, T2, T3, T4> ConvertOneOf<T1, T2, T3, T4>(this OneOf<T2, T3, T4> oneOf)
{
return oneOf.Match<OneOf<T1, T2, T3, T4>>(x => x, x => x, x=> x);
}
}
它不是特别漂亮,但它应该使您的代码相对干净。