简体   繁体   English

C#将元素添加到集合

[英]C# Adding element to collection

I'm trying to add an XmlElement to XmlElement[] but this seems to be impossible. 我正在尝试将XmlElement添加到XmlElement [],但这似乎是不可能的。

the errormessage: 错误消息:

Cannot implicitly convert type 'System.Xml.XmlElement' to 'System.Xml.XmlElement[]' 无法将类型'System.Xml.XmlElement'隐式转换为'System.Xml.XmlElement []'

The XmlElement[] object does not have an Add or Insert function XmlElement []对象没有添加或插入功能

so how can I do this? 那我该怎么办呢?

Update with code: 用代码更新:

This part is created from an XSD private System.Xml.XmlElement[] anyField; 这部分是从XSD私有System.Xml.XmlElement [] anyField创建的;

    /// <remarks/>
    [System.Xml.Serialization.XmlAnyElementAttribute()]
    public System.Xml.XmlElement[] Any
    {
        get
        {
            return this.anyField;
        }
        set
        {
            this.anyField = value;
        }
    }

Here I am trying to create the object and add a UniversalShipment to the Any collection. 在这里,我试图创建对象并将UniversalShipment添加到Any集合中。

    UniversalInterchangeBody body = new UniversalInterchangeBody();
    UniversalShipmentData shipmentData = new UniversalShipmentData();
    XmlElement universalShipmentXML = SerializeToXmlElement(shipmentData);
    body.Any = universalShipmentXML;

    public static XmlElement SerializeToXmlElement(object o)
    {
        XmlDocument doc = new XmlDocument();

        using (XmlWriter writer = doc.CreateNavigator().AppendChild())
        {
            new XmlSerializer(o.GetType()).Serialize(writer, o);
        }
        return doc.DocumentElement;
    }

I would use a List. 我会使用一个列表。

List<XmlElement> elements = new List<XmlElement>();
elements.Add(xamlElement);

An array is pre-sized with default elements in all entries of the array. 预先调整数组的大小,并在数组的所有条目中使用默认元素。 You cannot re-size the array by inserting/adding (if you do want to do this use a List<T> instead). 您不能通过插入/添加来调整数组的大小(如果确实要这样做,请使用List<T>代替)。 Otherwise simply set the value of an entry at a specific index: 否则,只需在特定索引处设置条目的值即可:

array[index] = value

Yes, it is indeed a copy of Add XmlElement to XmlElement [] dynamically sorry for this! 是的,的确是将XmlElement添加到XmlElement []的副本,对此深感抱歉!

as for the solution to my code in this case: 至于在这种情况下我的代码的解决方案:

var uShipmentCollection = new UniversalShipmentData[]
{
    shipmentData
};

Thanks for the duplicate reference Gusdor! 感谢您提供重复的Gusdor参考!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM