使用 Type 变量声明变量 [英] Declare a variable using a Type variable

查看:35
本文介绍了使用 Type 变量声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

Type leftType = workItem[LeftFieldName].GetType();

然后我想声明一个该类型的变量:

I then want to declare a variable of that type:

leftType someVar;

这可能吗?

推荐答案

您可以执行类似操作并将它们转换为已知接口.

You can do something like these and cast them to a known interface.

var someVar = Convert.ChangeType(someOriginalValue, workItem[LeftFieldName].GetType());
var someVar = Activator.CreateInstance(workItem[LeftFieldName].GetType());

如果您将 var 替换为 dynamic(并且您使用的是 .Net 4),您可以在 someVar 上调用您期望的方法目的.如果它们不存在,您只会得到一个 MissingMethodException.

If you replace var with dynamic (and you are using .Net 4), you can call the methods you expect on the someVar object. If they don't exist, you'll just get a MissingMethodException.

这篇关于使用 Type 变量声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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