-1

我得到了一个由 VS2010 的 XSD.exe 创建的类。

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.269
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.1.
// 

namespace ConsoleApplication1
{
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class transfer
    {

        private string sourceGLNField;

        private string destinationGLNField;

        private string actionTypeField;

        private string shipToField;

        private string documentNumberField;

        private string documentDateField;

        private string noteField;

        private string versionField;

        private transferCarrier[] carrierField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string sourceGLN
        {
            get
            {
                return this.sourceGLNField;
            }
            set
            {
                this.sourceGLNField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string destinationGLN
        {
            get
            {
                return this.destinationGLNField;
            }
            set
            {
                this.destinationGLNField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string actionType
        {
            get
            {
                return this.actionTypeField;
            }
            set
            {
                this.actionTypeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string shipTo
        {
            get
            {
                return this.shipToField;
            }
            set
            {
                this.shipToField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string documentNumber
        {
            get
            {
                return this.documentNumberField;
            }
            set
            {
                this.documentNumberField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string documentDate
        {
            get
            {
                return this.documentDateField;
            }
            set
            {
                this.documentDateField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string note
        {
            get
            {
                return this.noteField;
            }
            set
            {
                this.noteField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string version
        {
            get
            {
                return this.versionField;
            }
            set
            {
                this.versionField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("carrier", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public transferCarrier[] carrier
        {
            get
            {
                return this.carrierField;
            }
            set
            {
                this.carrierField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class transferCarrier
    {

        private transferCarrierProductList[] productListField;

        private string carrierLabelField;

        private string containerTypeField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("productList", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public transferCarrierProductList[] productList
        {
            get
            {
                return this.productListField;
            }
            set
            {
                this.productListField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string carrierLabel
        {
            get
            {
                return this.carrierLabelField;
            }
            set
            {
                this.carrierLabelField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string containerType
        {
            get
            {
                return this.containerTypeField;
            }
            set
            {
                this.containerTypeField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class transferCarrierProductList
    {

        private transferCarrierProductListSerialNumber[] serialNumberField;

        private string expirationDateField;

        private string lotNumberField;

        private string gTINField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("serialNumber", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable = true)]
        public transferCarrierProductListSerialNumber[] serialNumber
        {
            get
            {
                return this.serialNumberField;
            }
            set
            {
                this.serialNumberField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string expirationDate
        {
            get
            {
                return this.expirationDateField;
            }
            set
            {
                this.expirationDateField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string lotNumber
        {
            get
            {
                return this.lotNumberField;
            }
            set
            {
                this.lotNumberField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string GTIN
        {
            get
            {
                return this.gTINField;
            }
            set
            {
                this.gTINField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class transferCarrierProductListSerialNumber
    {

        private string valueField;

        /// <remarks/>
        [System.Xml.Serialization.XmlTextAttribute()]
        public string Value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class NewDataSet
    {

        private transfer[] itemsField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("transfer")]
        public transfer[] Items
        {
            get
            {
                return this.itemsField;
            }
            set
            {
                this.itemsField = value;
            }
        }
    }

}

我也有一个这样的控制台应用程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load xml file
            using (FileStream xmlStream = new FileStream("C:\\SaleReturn01.xml", FileMode.Open))
            {
                //Read xml file
                using (XmlReader xmlReader = XmlReader.Create(xmlStream))
                {
                    //Serialize xml with class which is created by XSD.exe in visual studio and set class with xmlfile
                    //In that case we don't need to xsd referenced validation
                    XmlSerializer serializer1 = new XmlSerializer(typeof(transfer));
                    transfer deserializedStudents = serializer1.Deserialize(xmlReader) as transfer;
                    showTransferClass(deserializedStudents);
                }
            }
        }

        public static void showTransferClass(transfer x)
        {
            try
            {
                FieldInfo[] myFields = typeof(transfer).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                foreach (FieldInfo field in myFields)
                {
                    if (!field.FieldType.IsArray)
                    {
                        Console.WriteLine("{0} : {1}", field.Name, field.GetValue(x));
                    }
                    else
                    {
                        Console.WriteLine("{0} : {1}", field.Name, "");
                        foreach (transferCarrier y in x.carrier)
                        {
                            showTransferCarierClass(y);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception : {0}", e.Message);
            }
        }

        public static void showTransferCarierClass(transferCarrier x)
        {
            try
            {
                FieldInfo[] myFields = typeof(transferCarrier).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                foreach (FieldInfo field in myFields)
                {
                    if (!field.FieldType.IsArray)
                    {
                        Console.WriteLine("  {0} : {1}", field.Name, field.GetValue(x));
                    }
                    else
                    {
                        Console.WriteLine("  {0} : {1}", field.Name, "");
                        foreach (transferCarrierProductList y in x.productList)
                        {
                            showTransferCarierProductListClass(y);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("  Exception : {0}", e.Message);
            }
        }

        public static void showTransferCarierProductListClass(transferCarrierProductList x)
        {
            try
            {
                FieldInfo[] myFields = typeof(transferCarrierProductList).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                foreach (FieldInfo field in myFields)
                {
                    if (!field.FieldType.IsArray)
                    {
                        Console.WriteLine("    {0} : {1}", field.Name, field.GetValue(x));
                    }
                    else
                    {
                        Console.WriteLine("    {0} : {1}", field.Name, "");
                        foreach (transferCarrierProductListSerialNumber y in x.serialNumber)
                        {
                            showTransferCarierProductListSerialNumberClass(y);

                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("    Exception : {0}", e.Message);
            }
        }

        public static void showTransferCarierProductListSerialNumberClass(transferCarrierProductListSerialNumber x)
        {
            try
            {
                FieldInfo[] myFields = typeof(transferCarrierProductListSerialNumber).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                foreach (FieldInfo field in myFields)
                {
                    if (!field.FieldType.IsArray)
                    {
                        Console.WriteLine("      {0} : {1}", field.Name, field.GetValue(x));
                    }
                    else
                    {
                        Console.WriteLine("      {0} : {1}", field.Name, "");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("      Exception : {0}", e.Message);
            }
        }
    }
}

总而言之,我可以获得字段的名称,但是每次我尝试获取字段的值时都会抛出这样的异常。现在我得到了真正的代码并且可以工作了。(谢谢 Jon Skeet)

你有什么想法来改进这段代码吗?

4

1 回答 1

1

嗯,是的......你打电话给:

temp = fld.GetValue(null);

从文档中FieldInfo.GetValue

如果字段是静态的,则忽略 obj。对于非静态字段,obj 应该是继承或声明该字段的类的实例。

那么,您要显示的字段是什么类型的实例?将其作为参数传递给GetValue. 如果没有实例,“字段的值”的概念就没有任何意义。这就像在说“什么是价值String.Length?” 不引用特定的字符串。

(另请注意,如果您遵循 .NET 命名约定,并且仅在首次使用时声明变量,限制它们的范围,您的代码会更清晰。)

于 2012-08-22T13:16:29.597 回答