使用类型变量转换对象 [英] cast object with a Type variable

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

问题描述

以下内容当然无效。有没有可能这样的方法呢?

  Type newObjectType = typeof(MyClass); 

var newObject =给定对象为newObjectType;


解决方案

newObjectType Type 类(包含有关该类型的元数据)的实例,而不是 type 本身。 / p>

这应该可行

  var newObject = namedObject as MyClass; 

OR

  var newObject =(MyClass)给定对象; 

由于编译时间,将类型强制转换为类型的实例确实没有任何意义>必须知道变量类型应该是什么,而类型的实例是运行时概念。



var 唯一可行的方法是在编译时知道变量的类型。






UPDATE



通常,铸造是一个编译时概念,即您必须在编译时知道类型。



类型转换是运行时概念。






UPDATE 2



如果您需要使用类型为变量的调用,并且在编译时不知道类型,则可以使用 reflection :在类型实例上使用 MethodInfo Invoke 方法。

  object myString = Ali; 
类型type = myString.GetType();
MethodInfo methodInfo = type.GetMethods()。Where(m => m.Name == ToUpper)。First();
对象被调用= methodInfo.Invoke(myString,null);
Console.WriteLine(已调用);
Console.ReadLine();


The following doesn't work, of course. Is there a possible way, which is pretty similar like this?

Type newObjectType = typeof(MyClass);

var newObject = givenObject as newObjectType;

解决方案

newObjectType is an instance of the Type class (containing metadata about the type) not the type itself.

This should work

var newObject = givenObject as MyClass;

OR

var newObject = (MyClass) givenObject;

Casting to an instance of a type really does not make sense since compile time has to know what the variable type should be while instance of a type is a runtime concept.

The only way var can work is that the type of the variable is known at compile-time.


UPDATE

Casting generally is a compile-time concept, i.e. you have to know the type at compile-time.

Type Conversion is a runtime concept.


UPDATE 2

If you need to make a call using a variable of the type and you do not know the type at compile time, you can use reflection: use Invoke method of the MethodInfo on the type instance.

object myString = "Ali";
Type type = myString.GetType();
MethodInfo methodInfo = type.GetMethods().Where(m=>m.Name == "ToUpper").First();
object invoked = methodInfo.Invoke(myString, null);
Console.WriteLine(invoked);
Console.ReadLine();

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

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