Implementing pattern matching in C#

后端 未结 5 1736
耶瑟儿~
耶瑟儿~ 2021-02-04 03:54

In Scala, you can use pattern matching to produce a result depending on the type of the input. For instance:

val title = content match {
    case blogPost: BlogP         


        
5条回答
  •  臣服心动
    2021-02-04 04:24

    In order to ensure total pattern matching, you would need to build the function into the type itself. Here's how I'd do it:

    public abstract class Content
    {
        private Content() { }
    
        public abstract T Match(Func convertBlog, Func convertPost);
    
        public class Blog : Content
        {
            public Blog(string title)
            {
                Title = title;
            }
            public string Title { get; private set; }
    
            public override T Match(Func convertBlog, Func 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(Func convertBlog, Func 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);
        }
    }
    

提交回复
热议问题