I am looking for a way to do arbitrary class instantion as well as attribute assignement and possibly method calling in .Net and preferrably C#. Since arbitrary is too broad a word let me tell you what I am after.
Let's say I have a DLL (objects.dll) that contains:
public class Person
{
// Field
public string name;
// Constructor that takes no arguments.
public Person()
{
name = "unknown";
}
// Constructor that takes one argument.
public Person(string nm)
{
name = nm;
}
// Method
public void SetName(string newName)
{
name = newName;
}
}
public class Table
{
// Field
public int width;
public int lenth;
public int height;
// Constructor that takes no arguments.
public Table()
{
width = 0;
length = 0;
height = 0
}
// Constructor that takes three arguments.
public Table(int w, int l, int h)
{
width = w;
length = l;
height = h;
}
// Method
public void SetWLH(int w, int l, int h)
{
width = w;
length = l;
height = h;
}
}
public class Printer
{
public Printer(){}
public void printAPerson(Person p)
{
//do stuff with p
}
public void printATable(Table t)
{
// do stuff with t
}
}
I want to be able to instantiate either of the classes above, set attribute values and call methods at runtime from a different program in the most generic possible. eg. lets say I hame a programm called myprog.exe, i want to be able to do the following
myprog.exe objects.dll Person name testname Printer printAPerson where:
-
objects.dll is the dll that contains all required classes
-
Person is the first I will instantiate name is its attribute
-
testname is the value I will assign to this attribute
-
Printer is the class I will use for printing
-
printAPerson is the method in the Printer class I need to call with the specified object as a parameter.
As you can see, in the best case for my use scenario, neither of the objects and classes are/will be known at compile time so I would like to be as non-casting as possible. If that is not possible I will take what I can.
I have seen this, How to use reflection to call a method and pass parameters whose types are unknown at compile time?, which to my limited knowledge kind of does what I want minus the casting bits or I could be mistaken.
Thanks a lot!
Aucun commentaire:
Enregistrer un commentaire