I am working on a C# application. I have a ClassLibrary
type project which has an interface and some classes which implement this interface. Code is:
public interface IUserInterface
{
String GetName();
int Function(int a, int b);
}
public class UserClass : IUserInterface
{
public String GetName() { return "Add"; }
public int Function(int a, int b) { return a + b; }
}
public class UserClass1 : IUserInterface
{
public String GetName() { return "Add"; }
public int Function(int a, int b) { return a + b; }
}
public class UserClass2 : IUserInterface
{
public String GetName() { return "Add"; }
public int Function(int a, int b) { return a + b; }
}
My requirement is that i have to find all the implementations of IUserInterface
, create the instances of those implementations using reflection and store all these instances in a List. My code for this is:
class Program
{
private static List<Type> nameTypeDict = new List<Type>();
private static List<IUserInterface> instances = new List<IUserInterface>();
static void Main(string[] args)
{
Program obj = new Program();
Assembly ass = Assembly.LoadFrom("ClassLibrary.dll");
foreach (Type t in ass.GetExportedTypes())
{
if (t.GetInterface("IUserInterface", true) != null)
{
Console.WriteLine("Found Type: {0}", t.Name);
nameTypeDict.Add(t);//Add to Dictonary
}
}
foreach (var type in nameTypeDict)
{
var typeObject = Activator.CreateInstance(type);
IUserInterface typeObj = (IUserInterface)typeObject;
instances.Add(typeObject);
}
Console.ReadKey();
}
}
I did manage to create the instance, but gets exception at
IUserInterface typeObj = (IUserInterface)typeObject;
The exception is:
System.InvalidCastException: 'Unable to cast object of type 'ClassLibrary.UserClass' to type 'ClassLibrary.IUserInterface'.'
How can this be resolved ? I know i am making some silly mistake but, i am unable to figure it out. The reason why i am casting it is because i have to save the instance in the IUserInterface
type list.
Aucun commentaire:
Enregistrer un commentaire