问题
I have this method:
public T GetInput<T>()
{
T result;
if( (typeof)T == Type.GetType("string"))
{
result = GetStringInput(); // returns a string
}
// Etc for a bunch of different types
}
The error I'm getting is that I can't implicitly cast a string to a "T". The point of the function is to be able to get input of any specified type and make sure to do type validation on the input before returning it. Ideas?
回答1:
You cannot simply assign variable of undetermined on compile time type T with string event if you are certain that it is correct code. Compiler will not allow it. To force this you can do this:
result = (T)(object)GetStringInput();
this dual cast will explicitly say to compiler that you take responsibility for this line.
回答2:
result = (T)(object)GetStringInput();
来源:https://stackoverflow.com/questions/12576770/casting-a-string-to-a-generic