Reflective Learning Series 3-reflection instance Application

Source: Internet
Author: User
Tags bool reflection

Example this thing is actually very difficult to make, get a simple, although can explain the problem but it is easy to let people feel no practical value, get a practical value but often involve many other technology even involve a lot of business logic, it seems very complex difficult to understand. Here I try to pursue a few examples that have practical value and are not complicated.

1. Use reflection to dynamically create objects of related classes by reading a configuration file

Let's take a look at the main function and the situation where the object that needs to be loaded dynamically is in the same assembly

Structure Chart:

Interface

interface ILog
  {
    bool Write(string message);
    bool Write(Exception ex);
  }

Textfilelog

class TextFileLog : ILog
  {
    public bool Write(string message)
    {
      string fileDir = ConfigurationManager.AppSettings["LogTarget"].ToString();
      using (StreamWriter w = File.AppendText(fileDir))
      {
        // w.Write(" Log Entry : ");
        w.WriteLine("发生时间{0}", DateTime.Now.ToLocalTime().ToString());
        w.WriteLine("日志内容为:{0}", message);
        w.WriteLine("-------------------------------");
        // Update the underlying file.
        w.Flush();
        w.Close();
      }
      return true;
    }
    public bool Write(Exception ex)
    {

      Write(ex.Message);
      return true;
    }
  }

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.