从String转换为<T>

Sai*_*ino 58 c# xml generics

我真的应该能够得到这个,但我只是觉得它更容易问.

在C#函数中:

public static T GetValue<T>(String value) where T:new()
{
   //Magic happens here
}
Run Code Online (Sandbox Code Playgroud)

什么是魔法的好实现?这背后的想法是我要解析xml并且所需的值通常是基元(bool,int,string等),这是使用泛型的完美地方......但是一个简单的解决方案目前正在躲避我.

顺便说一下,这是我需要解析的xml示例

<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>
Run Code Online (Sandbox Code Playgroud)

Sam*_*uel 156

我建议您不要尝试自己解析XML,而是尝试创建可以从XML反序列化到类中的类.我强烈建议遵循bendewey的回答.

但如果你不能这样做,那就有希望了.你可以用Convert.ChangeType.

public static T GetValue<T>(String value)
{
  return (T)Convert.ChangeType(value, typeof(T));
}
Run Code Online (Sandbox Code Playgroud)

并使用这样的

GetValue<int>("12"); // = 12
GetValue<DateTime>("12/12/98");
Run Code Online (Sandbox Code Playgroud)


wom*_*omp 6

你可以从大致这样的东西开始:

TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
   return (T)converter.ConvertFrom(value);
}
Run Code Online (Sandbox Code Playgroud)

如果你必须解析特殊类型的属性,比如颜色或文化字符串或诸如此类的东西,你当然必须在上面构建特殊情况.但这将处理大多数原始类型.