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

前端 未结 5 927
别跟我提以往
别跟我提以往 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:13

    No, you cannot. C# does not implement duck typing.

    You must implement an interface and cast to it.

    (However there are attempts to do it. Look at Duck Typing Project for an example.)

提交回复
热议问题