在C#中实现模式匹配

18
在Scala中,您可以使用模式匹配来根据输入的类型生成结果。例如:
val title = content match {
    case blogPost: BlogPost => blogPost.blog.title + ": " + blogPost.title
    case blog: Blog => blog.title
}

在C#中,我希望能够写出以下代码:

var title = Visit(content,
    (BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title,
    (Blog blog) => blog.Title
);

这个可行吗?当我尝试将其编写为单个方法时,我不知道如何指定泛型。以下实现看起来是正确的,除了让类型检查器允许接受T子类型的函数:

    public TResult Visit<T, TResult>(T value, params Func<T, TResult>[] visitors)
    {
        foreach (var visitor in visitors)
        {
            if (visitor.Method.GetGenericArguments()[0].IsAssignableFrom(value.GetType()))
            {
                return visitor(value);
            }
        }
        throw new ApplicationException("No match");
    }

我最接近的方法是将函数逐个添加到对象中,然后对值调用visit:
    public class Visitor<T, TResult>
    {
        private class Result
        {
            public bool HasResult;
            public TResult ResultValue;
        }

        private readonly IList<Func<T, Result>> m_Visitors = new List<Func<T, Result>>();

        public TResult Visit(T value)
        {
            foreach (var visitor in m_Visitors)
            {
                var result = visitor(value);
                if (result.HasResult)
                {
                    return result.ResultValue;
                }
            }
            throw new ApplicationException("No match");
        }

        public Visitor<T, TResult> Add<TIn>(Func<TIn, TResult> visitor) where TIn : T
        {
            m_Visitors.Add(value =>
            {
                if (value is TIn)
                {
                    return new Result { HasResult = true, ResultValue = visitor((TIn)value) };
                }
                return new Result { HasResult = false };
            });
            return this;
        }
    }

这可以这样使用:
var title = new Visitor<IContent, string>()
    .Add((BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title)
    .Add((Blog blog) => blog.Title)
    .Visit(content);

有没有想法可以用单个方法调用来实现这个?

2
有点像一个字典,其中键是类型,值是函数... - Roly
1
你使用的是C# 3还是4?在C# 4中,Func类型在其形式参数类型上是反变的,这为您转换提供了更多的灵活性。 - Eric Lippert
@Eric Lippert:在这种情况下,我认为实际上我想要协变而不是逆变。我希望接受可能无法接受类型为T的参数的函数(而通常您希望接受接受类型为T的参数的任何函数,包括接受类型为U的参数的函数,其中T <: U)。 - Michael Williamson
@Michael:如果你想在委托类型上使用不安全协变性,那么你可能会遇到一些困难。类型系统的设计是为了帮助你防止这种情况发生,而不是帮助你实现它。 - Eric Lippert
文章:如何使用正则表达式和Visual C#匹配模式 http://support.microsoft.com/kb/308252/en-us ,也许这会对某些人有所帮助。 - Mickey Tin
显示剩余2条评论
5个回答

13

模式匹配是功能编程语言(比如F#)中常见的一种有趣特性。在 codeplex 上有一个很棒的项目叫做Functional C#。 以下是一段 F# 代码示例:

let operator x = match x with
                 | ExpressionType.Add -> "+"

let rec toString exp = match exp with
                       | LambdaExpression(args, body) -> toString(body)
                       | ParameterExpression(name) -> name
                       | BinaryExpression(op,l,r) -> sprintf "%s %s %s" (toString l) (operator op) (toString r)

使用Functional C#库,C#的等效写法为:

var Op = new Dictionary<ExpressionType, string> { { ExpressionType.Add, "+" } };

Expression<Func<int,int,int>> add = (x,y) => x + y;

Func<Expression, string> toString = null;
 toString = exp =>
 exp.Match()
    .With<LambdaExpression>(l => toString(l.Body))
    .With<ParameterExpression>(p => p.Name)
    .With<BinaryExpression>(b => String.Format("{0} {1} {2}", toString(b.Left), Op[b.NodeType], toString(b.Right)))
    .Return<string>();

9

使用函数式C#(来自@Alireza)

var title = content.Match()
   .With<BlogPost>(blogPost => blogPost.Blog.Title + ": " + blogPost.Title)
   .With<Blog>(blog => blog.Title)
   .Result<string>();

Functional C#似乎使用了我所使用的相同方法,即在单独的方法调用中传递每个lambda,这表明在单个方法调用中完成所有操作似乎是不可能的(至少在保持类型安全的同时)。啊,好吧。 - Michael Williamson

5
为了确保完全的模式匹配,你需要将函数构建到类型本身中。这是我会这样做的:
public abstract class Content
{
    private Content() { }

    public abstract T Match<T>(Func<Blog, T> convertBlog, Func<BlogPost, T> convertPost);

    public class Blog : Content
    {
        public Blog(string title)
        {
            Title = title;
        }
        public string Title { get; private set; }

        public override T Match<T>(Func<Blog, T> convertBlog, Func<BlogPost, T> convertPost)
        {
            return convertBlog(this);
        }
    }

    public class BlogPost : Content
    {
        public BlogPost(string title, Blog blog)
        {
            Title = title;
            Blog = blog;
        }
        public string Title { get; private set; }
        public Blog Blog { get; private set; }

        public override T Match<T>(Func<Blog, T> convertBlog, Func<BlogPost, T> convertPost)
        {
            return convertPost(this);
        }
    }

}

public static class Example
{
    public static string GetTitle(Content content)
    {
        return content.Match(blog => blog.Title, post => post.Blog.Title + ": " + post.Title);
    }
}

这本质上是访问者模式的实现,只不过你传递了两个lambda而不是一个有两个方法的类。 - Jeff Walker Code Ranger

1

请查看我的模式匹配实现:repo

它基于表达式,因此提供与嵌套if相同的性能。

使用示例:

string s1 = "Hello";
string s2 = null;

Func<Option<string>> match = new Matcher<Option<string>>
{
     {s => s is None, s => Console.WriteLine("None")},
     {s => s is Some, s => Console.WriteLine((string)s) // or s.Value
};

match(s1); // Hello
match(s2); // None

可通过 NuGet 获得:Nuget 包


0

我正在使用的通用实现,可以匹配类型、条件或值:

public static class Match
{
    public static PatternMatch<T, R> With<T, R>(T value)
    {
        return new PatternMatch<T, R>(value);
    }

    public struct PatternMatch<T, R>
    {
        private readonly T _value;
        private R _result;

        private bool _matched;

        public PatternMatch(T value)
        {
            _value = value;
            _matched = false;
            _result = default(R);
        }

        public PatternMatch<T, R> When(Func<T, bool> condition, Func<R> action)
        {
            if (!_matched && condition(_value))
            {
                _result = action();
                _matched = true;
            }

            return this;
        }

        public PatternMatch<T, R> When<C>(Func<C, R> action)
        {
            if (!_matched && _value is C)
            {
                _result = action((C)(object)_value);
                _matched = true;
            }
            return this;
        }


        public PatternMatch<T, R> When<C>(C value, Func<R> action)
        {
            if (!_matched && value.Equals(_value))
            {
                _result = action();
                _matched = true;
            }
            return this;
        }


        public R Result => _result;

        public R Default(Func<R> action)
        {
            return !_matched ? action() : _result;
        }
    }
}

而在你的情况下,使用将会是这样的:

Match.With<IContent, string>(content)
     .When<BlogPost>(blogPost => blogPost.Blog.Title)
     .When<Blog>(blog => blog.Title)
     .Result; // or just .Default(()=> "none");

其他一些示例:

var result = Match.With<IFoo, int>(new Foo() { A = 5 })
    .When<IFoo>(foo => foo.A)
    .When<IBar>(bar => bar.B)
    .When<string>(Convert.ToInt32)
    .Result;
Assert.Equal(5, result);

var result = Match.With<int, string>(n)
    .When(x => x > 100, () => "n>100")
    .When(x => x > 10, () => "n>10")
    .Default(() => "");
Assert.Equal("n>10", result);

 var result = Match.With<int, string>(5)
     .When(1, () => "1")
     .When(5, () => "5")
     .Default(() => "e");
 Assert.Equal("5", result);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接