从字符串转换为< T> [英] Converting from String to <T>

查看:151
本文介绍了从字符串转换为< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的应该能够得到这一点,但我只是在那里我觉得这是比较容易问点。



在C#函数

 公共静态牛逼的GetValue< T>(字符串值)其中T:新的()
{
//魔术在这里发生
}

什么是对魔术一个很好的执行?这背后的想法是,我对XML解析和所需的值往往是原语(BOOL,INT,字符串,等等),这是使用泛型完美的地方......但是一个简单的解决方案是在那一刻我规避



顺便说一句,这里是我需要解析XML的样本

 <项目> 
<项目>
<&的ItemType GT; PIANO< /&的ItemType GT;
<名称>一种雅马哈钢琴< /名称>
<性状>
< allowUpdates>假LT; / allowUpdates>
< allowCopy>真< / allowCopy>
< /性状>
< /项目>
<项目>
<&的ItemType GT; PIANO_BENCH< /&的ItemType GT;
<名称>一种黑色的钢琴凳< /名称>
<性状>
< allowUpdates>真< / allowUpdates>
< allowCopy>假LT; / allowCopy>
< URL> www.yamaha.com< / URL>
< /性状>
< /项目>
<项目>
<&的ItemType GT; DESK_LAMP< /&的ItemType GT;
<名称>一种Verilux台灯< /名称>
<性状>
< allowUpdates>真< / allowUpdates>
< allowCopy>真< / allowCopy>
<数量> 2'; /数量>
< /性状>
< /项目>
< /项目>


解决方案

我会建议,而不是试图解析XML自己,您尝试创建一个能够从XML到反序列化班班。我会强烈推荐以下bendewey的回答。



但是,如果你不能做到这一点,是有希望的。您可以使用 Convert.ChangeType

 公共静态牛逼的GetValue< T>(字符串值)
{
回报率(T)的转换。一changeType(值的typeof(T));
}

和使用像这样

 的GetValue< INT>(12); // = 2 
的GetValue<&日期时间GT(98年12月12日);


I really should be able to get this, but I'm just to the point where I think it'd be easier to ask.

In the C# function:

public static T GetValue<T>(String value) where T:new()
{
   //Magic happens here
}

What's a good implementation for the magic? The idea behind this is that I have xml to parse and the desired values are often primitives (bool, int, string, etc.) and this is the perfect place to use generics... but a simple solution is eluding me at the moment.

btw, here's a sample of the xml I'd need to parse

<Items>
    <item>
    	<ItemType>PIANO</ItemType>
    	<Name>A Yamaha piano</Name>
    	<properties>
    		<allowUpdates>false</allowUpdates>
    		<allowCopy>true</allowCopy>
    	</properties>	
    </item>
    <item>
    	<ItemType>PIANO_BENCH</ItemType>
    	<Name>A black piano bench</Name>
    	<properties>
    		<allowUpdates>true</allowUpdates>
    		<allowCopy>false</allowCopy>
    		<url>www.yamaha.com</url>
    	</properties>
    </item>
    <item>
    	<ItemType>DESK_LAMP</ItemType>
    	<Name>A Verilux desk lamp</Name>
    	<properties>
    		<allowUpdates>true</allowUpdates>
    		<allowCopy>true</allowCopy>
    		<quantity>2</quantity>
    	</properties>
    </item>
</Items>

解决方案

I would suggest instead of trying to parse XML yourself, you try to create classes that would deserialize from the XML into the classes. I would strongly recommend following bendewey's answer.

But if you cannot do this, there is hope. You can use Convert.ChangeType.

public static T GetValue<T>(String value)
{
  return (T)Convert.ChangeType(value, typeof(T));
}

And use like so

GetValue<int>("12"); // = 2
GetValue<DateTime>("12/12/98");

这篇关于从字符串转换为&lt; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆