Consider the Following Classes
class Greeting // Which will act as Parent Class
{
public Greeting()
{ Console.WriteLine("I am in Greeting Class"); }
}
class bye : Greeting// Child Class of Greeting
{
public bye() { Console.WriteLine("I am in Class Bye"); }
}
class Hello : Greeting// Child Class of Greeting
{
public Hello() { Console.WriteLine("I am in Class Hello"); }
Now put these classes refernces in a XML document
<?xml version="1.0" encoding="utf-8" ?>
<Classes>
<Class code="100" path="InvokingConstructorsAssembly.ByeClass.bye"></Class>
<Class code="200" path="InvokingConstructorsAssembly.HelloClass.Hello"></Class>
</Classes>
Here is the Main Code where the classes references are loaded from XML document dynamically.
class Program
{
// Dictionary for containing classes refernce loaded from XML
public static Dictionary<string, string> tranDict;
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load(System.IO.Path.Combine(@"D:\Learning\InvokingConstructorsAssembly\InvokingConstructorsAssembly", "Classes.xml"));
XmlNodeList listClass = doc.DocumentElement.SelectNodes("Class");
tranDict = new Dictionary<string, string>();
foreach (XmlNode nodeTran in listClass)
{
string tranCode = nodeTran.Attributes["code"].InnerText;
string className = nodeTran.Attributes["path"].InnerText;
if (string.IsNullOrEmpty(tranCode) || string.IsNullOrEmpty(className))
throw new Exception("Code or class name is not given in Classes config file");
tranDict.Add(tranCode, className);
}
GetClass("100");
GetClass("200");
}
public static Greeting GetClass(string Code)
{
Assembly assem = Assembly.GetExecutingAssembly();
Type t = assem.GetType(tranDict[Code]);
Greeting gret = (Greeting)Activator.CreateInstance(t);
return gret;
}Output
I am in Greetin Class
I am in Class Bye
I am in Greeting Class
I am in Class Hello
Press any key to continue . . .
postingan yang bagus tentang How to Initiates an Object without using a new Keyword
ReplyDelete