您可以使用反射来实现这一点(的情况下,你不能/不想使用的界面)
假设你有对象集合“myObjects”不仅名字
foreach(object Obj in myObjects)
{
//depending on the visibility of your method you may need Bindings flags
MethodInfo dynMethod = Obj.GetType().GetMethod("getStatus");
var status = (string)dynMethod.Invoke(Obj, null);
//with parameters => dynMethod.Invoke(this, new object[] { methodParams });
}
在你不得不类/类型名你应该使用类似这样的情况下
(未经测试,但应工作):
String[] names = new String[] {"a", "b", "c"};
foreach (string name in names) {
Assembly assembly = Assembly.LoadFile("...Assembly.dll");
Type type = assembly.GetType(name);//name should be the full type name (Namespace.ClassName)
//here you get your Object instance
object Obj= Activator.CreateInstance(type, null);
MethodInfo dynMethod= Obj.GetType().GetMethod("getStatus");
var status = (string)dynMethod.Invoke(Obj, null);
}
不使用'dynamic'for这一点。使用继承! – DrKoch 2015-04-02 09:18:00
我从这篇文章的想法http://stackoverflow.com/questions/29406856/shapeless-objects-in-c-sharp – Ctrlfreak 2015-04-02 09:20:14
你想通过它的名称调用一个方法,或者你想通过它的名称获得一个对象,然后从它调用.getStatus()方法? – 2015-04-02 09:25:13