将变量转换为Type并调用Methods

时间:2013-05-24 13:15:56

标签: c# reflection types casting keyvaluepair

在将其转换为Type后,如何调用Object的方法调用? 我有一个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();
    }  

有什么办法吗?

感谢。

4 个答案:

答案 0 :(得分:1)

而不是

return v.someMethod();

你必须通过反射来调用方法

var method = typeof(v).GetMethod("<methodName>",...);

return method.Invoke(v, new[]{<parameters of the method>});

请注意method.Invoke()将返回一个对象,因此您必须将其强制转换为所需的类型(如果需要)。

答案 1 :(得分:1)

最简单的方法是使用dynamic关键字:

dynamic v = client.Value;
v.SomeMethod();

答案 2 :(得分:0)

最快的方法是,如果您没有批量处理某些事情,请使用Type.InvokeMember方法并使用正确的BindingFlags

答案 3 :(得分:0)

如果v.someMethod()中的someMethod相同,那么你的密钥可以实现一个接口 - 因此你可以取消Convert.ChangeType逻辑。