我想结合使用反射和动态。假设我有以下调用
dynamic foo = External_COM_Api_Call()
访问我使用COM接收的对象。
现在我想做一些这样的事情:
String bar = foo.GetType().GetProperty("FooBar").GetValue(foo,null)
但是我总是得到PropertyInfo为空的结果。
想法?
发布于 2010-12-22 22:13:05
既然可以直接使用反射,为什么还要使用反射:
dynamic foo = External_COM_Api_Call();
string value = foo.FooBar;这就是dynamic关键字的意义所在。您不再需要反射。
如果你想使用反射,那么不要使用动态:
object foo = External_COM_Api_Call();
string bar = (string)foo
.GetType()
.InvokeMember("FooBar", BindingFlags.GetProperty, null, foo, null);下面是一个完整的工作示例:
class Program
{
static void Main()
{
var type = Type.GetTypeFromProgID("WScript.Shell");
object instance = Activator.CreateInstance(type);
var result = (string)type
.InvokeMember("CurrentDirectory", BindingFlags.GetProperty, null, instance, null);
Console.WriteLine(result);
}
}https://stackoverflow.com/questions/4509986
复制相似问题