转换为以字符串格式给出的数据类型 [英] 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.
我想要达到的目标:
我有两个字符串,'a' 和 'b'.字符串 'a' 包含一个数据类型,例如Boolean".
字符串 b 包含1"或False"之类的值,可以是任何值.
我希望能够将字符串 'b' 的值存储在数据类型为字符串 'a' 的变量中.
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'.
}
}
或多或少我正在寻找一些奇怪的 TryParse() 黑客版本.
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
- 字符串
- 布尔值
- 浮点数,十进制
- 日期时间
我的问题:
是否有可能以任何方式(尝试)将值转换为字符串中给定的任何数据类型?
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.
推荐答案
您必须将字符串映射到类型.由于并非所有这些都是 System.
直接,我会考虑创建一个映射:
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.
然后,使用 Convert.ChangeType 来获取您的对象:
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));
这篇关于转换为以字符串格式给出的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!