在C#中实现模式匹配

时间:2011-05-17 13:32:26

标签: c# pattern-matching

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

我最接近的是将函数单独添加到对象,然后调用值访问:

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

知道如何使用单个方法调用来完成此操作吗?

5 个答案:

答案 0 :(得分:14)

模式匹配是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>();

答案 1 :(得分:9)

使用Functional C#(来自@Alireza)

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

答案 2 :(得分: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);
    }
}

答案 3 :(得分:1)

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

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

使用示例:

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 package

答案 4 :(得分:0)

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

export class YourComponent {
   constructor(private _ngZone: NgZone) {}

在您的情况下,使用情况如下:

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