简体   繁体   English

使用 Type 变量声明变量

[英]Declare a variable using a Type variable

I have this code:我有这个代码:

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

I then want to declare a variable of that type:然后我想声明一个该类型的变量:

leftType someVar;

Is that possible?那可能吗?

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());

If you replace var with dynamic (and you are using .Net 4), you can call the methods you expect on the someVar object.如果您用dynamic替换var (并且您使用的是 .Net 4),您可以在 someVar 对象上调用您期望的方法。 If they don't exist, you'll just get a MissingMethodException.如果它们不存在,您只会得到一个 MissingMethodException。

This is not possible.这不可能。

Variable types are a compile-time concept;变量类型是一个编译时概念; it would make no sense to declare a variable of a type which is not known until runtime .声明一个直到运行时才知道的类型的变量是没有意义的。
You wouldn't be able to do anything with the variable, since you wouldn't know what type it is.您将无法对变量执行任何操作,因为您不知道它是什么类型。

You're probably looking for the dynamic keyword.您可能正在寻找dynamic关键字。

No, that is not possible.不,那是不可能的。 The type of a variable has to be known at compile time.必须在编译时知道变量的类型。

You can declare a variable of type object , it will be capable of storing any data type.您可以声明一个object类型的变量,它将能够存储任何数据类型。

You cannot do that.你不能这样做。

You could use the dynamic type for .Net 4, but for earlier .Net versions, the only type that will fit is object , which you will need to manually cast later by again testing .GetType() on what you assigned to the object -typed variable.您可以将动态类型用于 .Net 4,但对于较早的 .Net 版本,唯一适合的类型是object ,稍后您需要通过再次测试.GetType()对分配给object内容进行手动.GetType() -类型变量。

Reading: SO link: whats-the-difference-between-dynamicc-4-and-var阅读: SO 链接:whats-the-difference-between-dynamicc-4-and-var

object x = Activator.CreateInstance(Type) will let you create the object. object x = Activator.CreateInstance(Type) 将让您创建对象。 Whether you can do much with it beyond that point, I'm not sure.在那之后你是否可以用它做很多事情,我不确定。

GetType is evaluated at run-time, and non- dynamic declaration is at compile-time (it does get more specific than that, yes), so no. GetType在运行时评估,非dynamic声明在编译时(它确实比这更具体,是的),所以不是。 Even var will require you to assign a value to it that is of unambiguous type.甚至var也会要求您为其分配一个明确类型的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM