Convert to a datatype given in string format

人走茶凉 提交于 2021-02-19 04:55:26

问题


I have been searching for a solution for quite a while now and couldn't find anything close.

What I want to achieve:
I have two strings, 'a' and 'b'. String 'a' contains a datatype, for example "Boolean".
String b contains a value like "1" or "False", could be anything.
I want to be able to store the value of string 'b' in a variable which has the datatype of string 'a'.

If I would itterate trough a list of results with the same values as given in the example the results would be as following:

Foreach(var value in MyList)
{
  if(!var ConvertTo a) //Result would be negative because for "1" for it is not a boolean value, however if 'a' is "Int32" the result would be true.
    continue;  
  else 
  {//The value "False" is convertable to boolean, so the result would true
    Create a variable with datatype boolean with the value 'false'.
  }
}

More or less i'm in search of some strangly hacked version of TryParse().

I used boolean in my example, but this can be any datatype. At least I should be able to handle atleast the following datatypes:

  • Int, Int32, Int64
  • string
  • Boolean
  • float, decimal
  • DateTime

My question:
Is it possible in any way to (try to) convert a value to any datatype given in a string?

I hope my question and example is clear, if not please leave a comment.


回答1:


You have to map the strings to a type. Since not all of them are System.<yourType> directly, I would consider creating a mapping:

Dictionary<string, Type> types = new Dictionary<string, Type>();
types.Add("int", typeof(System.Int32);
//etc.

Then, use Convert.ChangeType to get your object:

object myObj = Convert.ChangeType(b, types[a]);

Maybe you could extend this by trying to get the type if the key does not exist in your type mapping:

object myObj = Convert.ChangeType(b, Type.GetType("System." + a));



回答2:


in general if you know the type name you can do this:

Type type = Type.GetType("System.Data.OleDb.OleDbParameter");

for example, so you must anyway know the full name of the type.

said so, if you have an object which was set from the caller to a certain value, you can do a GetType() on the object and get its actual type.

if "True" comes as string, you have no way to distinguish if should be a bool or a string.




回答3:


If you want to use the TimeSpan datatype, you cannot use ChangeType().

An alternative is to use TypeConverter.ConvertFrom():

var asString = "0";
var textType = "System.Int32";

var dataType = Type.GetType(textType);
var converter = TypeDescriptor.GetConverter(dataType);
var newValue = converter.CanConvertFrom(asString) ? 
    converter.ConvertFrom(asString) :
    asString;

As with the other answers, it assumes you know what type you're casting to.



来源:https://stackoverflow.com/questions/7266963/convert-to-a-datatype-given-in-string-format

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