Home > Net >  Reflection is not referenced DLL, can create instances of the class to interface
Reflection is not referenced DLL, can create instances of the class to interface

Time:04-16

Ask your bosses, I now have a demand, a project in the future will be used for several products, so want to through the config file to replace different DLL name and the name of the class, to invoke the various products require unique function, to avoid modifying the entire program,
Because the name of the class is not fixed, so want to change into interface to use, but the actual use is always an error,
Want to ask is why an error? And how to modify to achieve this requirement? Below is a simplified example



DLL example
 
The namespace DemoDll
{
Public class Product1: IProduct
{
Public string name {get=& gt; "Product name"; }
Public string GetInfo ()
{
//retrieved from the database product information
Return "product information... ";
}
Public void PrintInfo ()
{
//call the printer
}
}
}


Interface example
 
Public interface IProduct
{
String name {get; }
String GetInfo ();
Void PrintInfo ();
}


The main program example
 
Private void Main ()
{
//DemoDll absolute path
String dll_path=ConfigurationManager. AppSettings (" path ");
//fully qualified name of a class, DemoDll Product1
String class_name.=ConfigurationManager AppSettings (" class ");

The Assembly assmbly=Assembly. LoadFrom (dll_path);
IProduct product=(IProduct) assmbly. CreateInstance (class_name);

//using the interface types as a function of the parameter
CheckProduct (product);
}


CodePudding user response:

IProduct interface above to namespace DemoInterface

CodePudding user response:

refer to the second floor kmiaoer response:
IProduct above the interface to the namespace DemoInterface

IProduct interface in the namespace is DemoInterface ah
  •  Tags:  
  • C#
  • Related