将类型转换为数组

Converting a type to an array

我正在为 Web 服务创建解析器。我遇到了障碍。

我有一个 XML 文档,它是

<AdvisorName>
  <PersonNameTitle>String[]</PersonNameTitle>
  <PersonGivenName>String[]</PersonGivenName>
  <PersonFamilyName>String</PersonFamilyName>
  <PersonNameSuffix>String[]</PersonNameSuffix>
  <PersonRequestedName>String</PersonRequestedName>
</AdvisorName>

我的密码是

foreach (XElement childNodeprop in childNodesPropLst)
{
    XElement childElement = childNodeprop.Element(prop.Name);

    if (childElement != null)
    {
        // Error happens at next line:
        prop.SetValue(obj, Convert.ChangeType(childElement.Value, prop.PropertyType), 
            null);

        break;
    }
}

如您所见,XML 的 return 类型是一个数组,它无法转换它。

完整代码附在此处

foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.SetProperty))
{
    if (!prop.Name.Equals("ExtensionData"))
    { 
        if (prop.PropertyType.IsPrimitive())
        {
            var childNodesPropLst = doc.Descendants(propertyName);
            foreach (XElement childNodeprop in childNodesPropLst)
            {
                XElement childElement = childNodeprop.Element(prop.Name);
                if (childElement != null)
                {
                    prop.SetValue(obj, Convert.ChangeType(childElement.Value, prop.PropertyType), null);
                    break;
                }
            }
        }
    }
}

我同意 Rufus 的观点,如果使用 .NET 的内置 XML 序列化 (Introducing XML Serialization),自定义 XML 反序列化可能不是必需的,但如果必须,您可以尝试使用类型转换器,例如:

var type = //get type
TypeDescriptor.GetConverter(type).ConvertFrom(stringSerialization);

我想我已经完成了我所做的

if (prop.PropertyType.IsArray )
                        {

                            ArrayList arrLst = new ArrayList();

                            var arrayElements = childNodeprop.Elements(prop.Name);

                            foreach(XElement element in arrayElements )
                            {
                                arrLst.Add(element.Value);
                            }
                            var  BaseElementType= prop.PropertyType.GetElementType();
                            prop.SetValue(obj, arrLst.ToArray(BaseElementType), null);


                        }
and it works..