开发者

Convert to a datatype given in string format

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 dataty开发者_开发知识库pe 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.


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));


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜