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