Cast a variable to a Type and call Methods

旧巷老猫 提交于 2019-12-24 16:28:43

问题


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();
    }  

Any way to do this?

Thanks.


回答1:


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).




回答2:


The simplest approach is to use the dynamic keyword:

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



回答3:


Quickest way, when you're not doing something in bulk, is using the Type.InvokeMember method with the right BindingFlags.




回答4:


If someMethod is going to be same in v.someMethod(), your keys could implement an interface - and hence you could do away with the Convert.ChangeType logic.



来源:https://stackoverflow.com/questions/16735887/cast-a-variable-to-a-type-and-call-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!