65.9K
CodeProject 正在变化。 阅读更多。
Home

C# - 数据传输对象

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (35投票s)

2004年11月18日

2分钟阅读

viewsIcon

300623

downloadIcon

2475

本文演示了如何使用可序列化的数据传输对象,在应用程序中传输数据。

引言

数据传输对象 (DTO) 是一种简单的可序列化对象,用于在应用程序的多个层之间传输数据。DTO 中包含的字段通常是基本类型,例如字符串、布尔值等。其他 DTO 也可以包含在 DTO 中或由 DTO 聚合。例如,您可能有一个包含在 LibraryDTO 中的 BookDTO 集合。我创建了一个由多个应用程序使用的框架,该框架利用 DTO 在不同层之间传输数据。该框架还依赖于其他 OO 模式,例如工厂模式、门面模式等。与 DataSet 相比,DTO 的一个优点是 DTO 不必直接匹配数据表或视图。DTO 可以聚合来自另一个 DTO 的字段。

使用代码

  1. 创建一个项目,该项目将供您的应用程序通用。
  2. 生成抽象基类 DTO
  3. 生成序列化助手类。
  4. 创建从 DTO 基类继承的派生 DTO。
  5. 创建控制台应用程序来测试您的 DTO 和序列化。

*** 注意:所有代码都可通过可下载的 zip 文件获得。***

所有数据传输对象的抽象基类

这是所有数据传输对象的基类。

using System;

namespace DEMO.Common
{
    /// 
    /// This is the base class for all DataTransferObjects.
    /// 
    public abstract class DTO
    {
        public DTO()
        {
        }
    }
}

数据传输对象序列化助手类

这是 DTO 的助手类。它具有用于序列化和反序列化 DTO 的公共方法。

using System;
using System.Xml.Serialization;
using System.IO;

namespace DEMO.Common
{
    /// 
    /// Summary description for DTOSerializerHelper.
    /// 
    public class DTOSerializerHelper
    {
        public DTOSerializerHelper()
        {
        }

        /// 
        /// Creates xml string from given dto.
        /// 
        /// DTO
        /// XML
        public static string SerializeDTO(DTO dto)
        {
            try
            {
                XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
                StringWriter sWriter = new StringWriter();
                // Serialize the dto to xml.
                xmlSer.Serialize(sWriter, dto);
                // Return the string of xml.
                return sWriter.ToString();
            }
            catch(Exception ex)
            {
                // Propogate the exception.
                throw ex;
            }
        }

        /// 
        /// Deserializes the xml into a specified data transfer object.
        /// 
        /// string of xml
        /// type of dto
        /// DTO
        public static DTO DeserializeXml(string xml, DTO dto)
        {
            try
            {
                XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
                // Read the XML.
                StringReader sReader = new StringReader(xml);
                // Cast the deserialized xml to the type of dto.
                DTO retDTO = (DTO)xmlSer.Deserialize(sReader);
                // Return the data transfer object.
                return retDTO;
            }
            catch(Exception ex)
            {
                // Propogate the exception.
                throw ex;
            }            
        }

    }
}

派生数据传输对象示例

DemoDTO 是从 DTO 基类继承的派生类。此类定义了一些简单的字段,例如 demoIddemoNamedemoProgrammer

using System;
using System.Xml.Serialization;
using DEMO.Common;

namespace DEMO.DemoDataTransferObjects
{
    /// 
    /// Summary description for the DemoDTO.
    /// 
    public class DemoDTO : DTO
    {
        // Variables encapsulated by class (private).
        private string demoId = "";
        private string demoName = "";
        private string demoProgrammer = "";

        public DemoDTO()
        {
        }

        ///Public access to the DemoId field.
        ///String
        [XmlElement(IsNullable=true)]
        public string DemoId
        {
            get
            {
                return this.demoId;
            }
            set
            {
                this.demoId = value;
            }
        }

        ///Public access to the DemoId field.
        ///String
        [XmlElement(IsNullable=true)]
        public string DemoName
        {
            get
            {
                return this.demoName;
            }
            set
            {
                this.demoName = value;
            }
        }

        ///Public access to the DemoId field.
        ///String
        [XmlElement(IsNullable=true)]
        public string DemoProgrammer
        {
            get
            {
                return this.demoProgrammer;
            }
            set
            {
                this.demoProgrammer = value;
            }
        }

    }
}

显示 DTO 示例的控制台应用程序

控制台应用程序演示了创建 DTO、序列化 DTO 和反序列化 DTO 是多么容易。

using System;
using DEMO.Common;
using DEMO.DemoDataTransferObjects;

namespace DemoConsoleApplication
{
    /// 
    /// Summary description for DemoClass.
    /// 
    public class DemoClass
    {
        public DemoClass()
        {
        }

        public void StartDemo()
        {
            this.ProcessDemo();
        }

        private void ProcessDemo()
        {
            DemoDTO dto = this.CreateDemoDto();
            
            // Serialize the dto to xml.
            string strXml = DTOSerializerHelper.SerializeDTO(dto);
            
            // Write the serialized dto as xml.
            Console.WriteLine("Serialized DTO");
            Console.WriteLine("=======================");
            Console.WriteLine("\r");
            Console.WriteLine(strXml);
            Console.WriteLine("\r");

            // Deserialize the xml to the data transfer object.
            DemoDTO desDto = 
              (DemoDTO) DTOSerializerHelper.DeserializeXml(strXml, 
              new DemoDTO());
            
            // Write the deserialized dto values.
            Console.WriteLine("Deseralized DTO");
            Console.WriteLine("=======================");
            Console.WriteLine("\r");
            Console.WriteLine("DemoId         : " + desDto.DemoId);
            Console.WriteLine("Demo Name      : " + desDto.DemoName);
            Console.WriteLine("Demo Programmer: " + desDto.DemoProgrammer);
            Console.WriteLine("\r");
        }

        private DemoDTO CreateDemoDto()
        {
            DemoDTO dto = new DemoDTO();
            
            dto.DemoId            = "1";
            dto.DemoName        = "Data Transfer Object Demonstration Program";
            dto.DemoProgrammer    = "Kenny Young";

            return dto;
        }
    }
}
using System;
using DEMO.Common;
using DEMO.DemoDataTransferObjects;

namespace DemoConsoleApplication
{
    /// 
    /// Summary description for MainClass.
    /// 
    class MainClass
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main(string[] args)
        {
            DemoClass dc = new DemoClass();
            dc.StartDemo();

        }
    }
}

输出

结论

本文演示了一种使用数据传输对象的简单方法。这些对象是为多个应用程序开发的通用框架的一小部分。该框架具有多个层,但一个贯穿始终的通用对象是 DTO。框架中存在将 DataReader 转换为数据访问对象的对象。待有时间时,我将发布更多关于企业架构的文档,并更详细地介绍该框架。

参考文献

  1. 企业应用架构模式,Martin Fowler 2003。
© . All rights reserved.