将变量强制转换为类型并调用方法 [英] Cast a variable to a Type and call Methods

查看:175
本文介绍了将变量强制转换为类型并调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于将变量强制转换为类型并调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆