可以将一个变量转换为存储在另一个变量类型? [英] Is possible to cast a variable to a type stored in another variable?

查看:88
本文介绍了可以将一个变量转换为存储在另一个变量类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我需要做的:

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



能像这样做吗?

Can something like this be done?

推荐答案

没有,你不能。 C#不执行鸭打字

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

您必须实现接口和投给它。

You must implement an interface and cast to it.

(但也有尝试这样做。看的Duck打字项目一个例子。)

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

这篇关于可以将一个变量转换为存储在另一个变量类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆