带有类型变量的强制转换对象 [英] cast object with a Type variable

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

问题描述

当然,以下是行不通的.有没有可能的方法,和这个很相似?

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;

推荐答案

newObjectTypeType 类的实例(包含关于类型)而不是类型本身.

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

这应该有效

var newObject = givenObject as MyClass;

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.

var 可以工作的唯一方法是在编译时知道变量的类型.

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

Casting 通常是一个编译时的概念,即您必须在编译时知道类型.

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

类型转换是一个运行时概念.

Type Conversion is a runtime concept.

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

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天全站免登陆