问题
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.
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();
... 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()
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
.
回答1:
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 is now your type argument.
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.
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.
回答2:
Since you will ultimately be assigning the cast to a 'Foo', you can just write
Foo beenCast = (Foo)castMe;
If 'castMe' is any other type than 'Foo' (or derived), the cast will fail anyway, it does matter what you are trying to cast it to.
回答3:
Thanks to Frank, I've been able to get the function I wanted to work, working. The function I ended up writing was:
Public Shared Function CastTypeOrNull(Of T)(ByVal castMe As Object) As T
If (castMe Is Nothing Or castMe.GetType Is GetType(System.DBNull)) Then
Return Nothing
Else
Return CType(castMe, T)
End If
End Function
... and I call it using:
varDateNullable = CastTypeOrNull(Of Nullable(Of Date))(row("DateTimeValue"))
Obviously you need to know the type you want to case to at compile time (I do), but it's a really nice shorthand to replace having to write a separate method for each different type you might want to cast to.
来源:https://stackoverflow.com/questions/1547594/cast-a-variable-to-a-type-represented-by-another-type-variable