Casting a string to a generic

只愿长相守 提交于 2019-12-12 20:25:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!