Using attribute and reflection to generate text messages from templates

Source: Internet
Author: User
Tags reflection

Generating text messages from templates is a more common requirement. To put it bluntly, it is how to replace the keyword in the SMS template and become the actual and meaningful text message.

For example, SMS template is as follows: "[Username], today is [date],[content]", that "[user name]", "[Date]", "[content]", is the keyword.

People would say, this is not easy, I write a function to replace the next line?

public string GetMsg(string template, string userName, string date, string content)
        {
            return template.Replace("[用户名]", userName).Replace("[日期]", date).Replace("[内容]", content);
        }

This, of course, is entirely achievable. But if there are a lot of templates and there are a lot of variables in the template, then write the replacement code will be soft

It? And it's not guaranteed to replace the keyword incorrectly.

Therefore, in order to solve the "replacement" of this repetitive and error-prone work, this paper proposes a solution: the use of attribute and reflection from the template to generate text messages.

The basic idea is: For each SMS template to write a host text message keyword content of the entity class, for the entity class each attribute plus description characteristics

(Attribute), through a helper class to get a < keyword, value > dictionary, and then replace according to the dictionary, get text messages.

Sample entity classes:

    public class Message
    {
        [Description("[用户名]")]
        public string UserName { get; set; }

        [Description("[内容]")]
        public string Content { get; set; }

        [Description("[日期]")]
        public string Date { get; set; }
    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.