将变量强制转换为类型并调用方法

编程入门 行业动态 更新时间:2024-10-25 20:22:18
本文介绍了将变量强制转换为类型并调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在将对象转换为类型后,如何调用对象的方法调用? 我有一个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();

更多推荐

将变量强制转换为类型并调用方法

本文发布于:2023-10-14 21:43:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492300.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   变量   类型   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!