将变量转换为由另一个Type变量表示的类型? [英] Cast a variable to a type represented by another Type variable?
问题描述
我知道这样的问题之前已被问过,我怀疑是可能的,但我只是想确保不是这样。
I'm aware that questions like this have been asked before and I doubt it's possible, but I just wanted to make 100% sure that it isn't.
在VB.net或C#(任一种语言,没有关系),我想把一个变量转换为另一个类型变量表示的类型。下面是C#中需要的代码类型的示例:
In VB.net or C# (either language, it doesn't matter), I want to cast a variable to a type represented by another Type variable. Here's an example of the kind of code that would be needed in C#:
Object castMe = new Foo();
Type castTo = typeof(Foo);
Foo beenCast = (castTo.GetRepresentedType())castMe;
beenCast.MethodInFoo();
...或在VB中,类似:
... or in VB, something like:
Dim castMe As Object = New Foo()
Dim castTo As Type = GetType(Foo)
Dim beenCast As Foo = CType(castMe, castTo.GetRepresentedType())
beenCast.MethodInFoo()
它将在运行时为cast类型参数返回一个Type,而不是一个实际的编译时类型(即 CType(castMe,Foo)
)。我不太明白为什么你不能这样做,虽然...肯定,运行时转换错误可能会导致,但你也可以得到他们,当你指定一个编译时类型。如果castMe不是Foo的实例,那么即使 CType(castMe,Foo)
仍然会抛出 InvalidCastException
。 / p>
The big problem is obviously specifying a method which will return a Type at runtime for the cast type argument, rather than an actual compile-time type (ie. CType(castMe, Foo)
). I don't quite understand why you can't do this, though... sure, runtime cast errors may result, but you can also get them when you DO specify a compile-time type. If castMe is not an instance of Foo, then even CType(castMe, Foo)
will still throw an InvalidCastException
.
推荐答案
如果您确实知道要投射的类型,像这样:
If you do know to which type you want to cast you will have to end up with something like this:
public static T Cast<T>(object o) {
return (T)o;
}
T现在是您的类型参数。
T is now your type argument.
如果不要知道所投递的类型,编译器也无法知道。这是一个静态类型语言为你。如果你不喜欢这样的事情,你可能想要有一个漫步,例如。 ruby。
If you don't know what the type is that you cast to, the compiler can't know either. That's a statically typed language for you. If you don't like such things you may want to have a wander through e.g. ruby.
在这种情况下,通常的响应是通过基类或接口的abstactions - 将常见的行为提取到可以在静态类型语言中使用的属性,事件和方法,即使你不知道在给定情况下的具体类型。
In cases like that, usual responses are abstactions via base classes or interfaces - extract common behaviour into properties, events and methods that can be used in a statically typed language, even though you don't know the specific type in a given situation.
这篇关于将变量转换为由另一个Type变量表示的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!