带有类型变量的强制转换对象 [英] cast object with a Type variable
问题描述
当然,以下是行不通的.有没有可能的方法,和这个很相似?
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
是 Type
类的实例(包含关于类型)而不是类型本身.
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屋!