本文介绍了将变量强制转换为类型并调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在将对象转换为类型后,如何调用对象的方法调用? 我有一个KeyValuePair存储对象的类型和对象本身。然后,我想将此对象转换为其键类型并调用该类类型的方法。
How would I go about invoking a method call for an Object after casting it to a Type? I have a KeyValuePair which stores the type of the object and the object itself. I then want to cast this object to its key type and invoke a method of that class type.
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(); }可以这样做吗?
谢谢。
推荐答案最简单的方法是使用 dynamic 关键字:
The simplest approach is to use the dynamic keyword:
dynamic v = client.Value; v.SomeMethod();更多推荐
将变量强制转换为类型并调用方法
发布评论