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

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

问题描述

这是我需要做的:

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

可以这样做吗?

推荐答案

不,你不能。 C#不实施鸭式打字

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

你必须实现一个接口并强制转换它。

You must implement an interface and cast to it.

(但是有尝试这样做,看看 Duck Typing Project 。)

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

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

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