本文整理匯總了C#中System.Runtime.Serialization.XsdDataContractImporter類的典型用法代碼示例。如果您正苦於以下問題:C# XsdDataContractImporter類的具體用法?C# XsdDataContractImporter怎麽用?C# XsdDataContractImporter使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
XsdDataContractImporter類屬於System.Runtime.Serialization命名空間,在下文中一共展示了XsdDataContractImporter類的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Main
//引入命名空間
using System;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Runtime.Serialization;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Globalization;
namespace XsdContractImporterExample
{
class Program
{
static void Main(string[] args)
{
try
{
XmlSchemaSet schemas = Export();
CodeCompileUnit ccu = Import(schemas);
CompileCode(ccu, "Person.cs");
CompileCode(ccu, "Person.vb");
}
catch (Exception exc)
{
Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace);
}
finally
{
Console.WriteLine("Press <Enter> to end....");
Console.ReadLine();
}
}
static XmlSchemaSet Export()
{
XsdDataContractExporter ex = new XsdDataContractExporter();
ex.Export(typeof(Person));
return ex.Schemas;
}
static CodeCompileUnit Import(XmlSchemaSet schemas)
{
XsdDataContractImporter imp = new XsdDataContractImporter();
// The EnableDataBinding option adds a RaisePropertyChanged method to
// the generated code. The GenerateInternal causes code access to be
// set to internal.
ImportOptions iOptions = new ImportOptions();
iOptions.EnableDataBinding = true;
iOptions.GenerateInternal = true;
imp.Options = iOptions;
if (imp.CanImport(schemas))
{
imp.Import(schemas);
return imp.CodeCompileUnit;
}
else
{
return null;
}
}
static void CompileCode(CodeCompileUnit ccu, string sourceName)
{
CodeDomProvider provider = null;
FileInfo sourceFile = new FileInfo(sourceName);
// Select the code provider based on the input file extension, either C# or Visual Basic.
if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".CS")
{
provider = new Microsoft.CSharp.CSharpCodeProvider();
}
else if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".VB")
{
provider = new Microsoft.VisualBasic.VBCodeProvider();
}
else
{
Console.WriteLine("Source file must have a .cs or .vb extension");
}
if (provider != null)
{
CodeGeneratorOptions options = new CodeGeneratorOptions();
// Set code formatting options to your preference.
options.BlankLinesBetweenMembers = true;
options.BracingStyle = "C";
StreamWriter sw = new StreamWriter(sourceName);
provider.GenerateCodeFromCompileUnit(ccu, sw, options);
sw.Close();
}
}
}
[DataContract]
public class Person
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
public Person(string newFName, string newLName)
{
FirstName = newFName;
LastName = newLName;
}
}
}