Is possible to cast a variable to a type stored in another variable?

前端 未结 5 963
别跟我提以往
别跟我提以往 2021-01-03 23:18

This is what I need to do:

object foo = GetFoo();
Type t = typeof(BarType);
(foo as t).FunctionThatExistsInBarType();

Can something like th

5条回答
  •  醉话见心
    2021-01-04 00:08

    You can use the Convert.ChangeType method.

    object foo = GetFoo(); 
    Type t = typeof(string);
    string bar = (string)Convert.ChangeType(foo, t);
    

提交回复
热议问题