简体   繁体   English

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

[英]Cast a variable to a Type and call Methods

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. 我有一个KeyValuePair,它存储对象的类型和对象本身。 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();
    }  

Any way to do this? 有什么办法吗?

Thanks. 谢谢。

instead of 代替

return v.someMethod();

you have to call the method by reflection 您必须通过反射调用该方法

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

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

Note that method.Invoke() will return an object, so you'll have to cast it to the desired type (if needed). 注意method.Invoke()将返回一个对象,因此您必须将其强制转换为所需的类型(如果需要)。

The simplest approach is to use the dynamic keyword: 最简单的方法是使用dynamic关键字:

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

当您不做大量工作时,最快的方法是将Type.InvokeMember方法与正确的BindingFlags

如果someMethod在v.someMethod()是相同的,则您的键可以实现一个接口-因此可以取消Convert.ChangeType逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM