我正在尋找一種方法來做任意類實例以及屬性指派和可能的方法調用在.Net和最好的C#。由於任意太寬泛的一個詞讓我告訴你我在做什麼。.net仲裁運行時類實例和方法調用
比方說,我有一個DLL(objects.dll),包含:
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
}
}
我希望能夠實例以上任一類,設置屬性值和調用方法在運行時從不同的程序在最通用的可能。例如。可以說,我哈默爾一個PROGRAMM稱爲MYPROG.EXE,我希望能夠做到以下幾點
MYPROG.EXE objects.dll人名測試名打印機printAPerson 其中:
objects.dll是包含所有必需的類
人是我第一次將實例名的dll是它的屬性
測試名是我將分配給此屬性的值
打印機是我將使用用於打印
printAPerson類是在打印機I類需要與指定對象作爲參數來調用該方法。
正如你所看到的,在我的使用情況最好的情況下,無論是對象和類是/將在編譯時是已知的,所以我想應該非鑄造成爲可能。如果這是不可能的,我會盡我所能。
我已經看到了這個,How to use reflection to call a method and pass parameters whose types are unknown at compile time?,這對我有限的知識類型做我想要的減去鑄造位或我可能會被誤認爲。
非常感謝!
您鏈接的問題對我的問題有所有答案。你對這篇文章有什麼不瞭解? – Juan
我在最後一句「減去鑄造位」中解釋它。該文特別要求ClassA aa = new ClassA();在開始時實例化。如果我可以逃避,我會更喜歡它。 – Zach