[英]Cast a variable to a Type and call Methods
将对象转换为类型后,如何调用对象的方法调用? 我有一个KeyValuePair,它存储对象的类型和对象本身。 然后,我想将此对象转换为其键类型并调用该类类型的方法。
KeyValuePair<Type, Object> client = myClients.Find(
delegate(KeyValuePair<Type, Object> result)
{
return (result.Key == myClients[clientNumber].Key); // Match client of the same type
}
);
if (client.Value != null)
{
// cast client.Value to type of client.Key, then invoke someMethod
client.Key.GetType() v = Convert.ChangeType(client.Value, client.Key.GetType());
return v.someMethod();
}
有什么办法吗?
谢谢。
代替
return v.someMethod();
您必须通过反射调用该方法
var method = typeof(v).GetMethod("<methodName>",...);
return method.Invoke(v, new[]{<parameters of the method>});
注意method.Invoke()
将返回一个对象,因此您必须将其强制转换为所需的类型(如果需要)。
最简单的方法是使用dynamic
关键字:
dynamic v = client.Value;
v.SomeMethod();
当您不做大量工作时,最快的方法是将Type.InvokeMember
方法与正确的BindingFlags
。
如果someMethod在v.someMethod()
是相同的,则您的键可以实现一个接口-因此可以取消Convert.ChangeType
逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.