C# 将#if/#endif指令添加到生成类的CodeTypeDefinition上的DataContract属性

C# 将#if/#endif指令添加到生成类的CodeTypeDefinition上的DataContract属性,c#,datacontract,codedom,C#,Datacontract,Codedom,我正在使用XSD->C#类解析器,它为我们的数据模型生成类,这些类将在WPF客户端和基于Silverlight web的部分之间共享 我们正在尝试使用[DataContract]属性扩充生成的类,这些属性只应在未定义SILVERLIGHT符号时使用,即: #if !SILVERLIGHT [DataContract] #endif public class Class1 { /* ... */ } 如何将此#if/#endif块添加到Class1的CodeTypeDefinition,或Dat

我正在使用XSD->C#类解析器,它为我们的数据模型生成类,这些类将在WPF客户端和基于Silverlight web的部分之间共享

我们正在尝试使用
[DataContract]
属性扩充生成的类,这些属性只应在未定义SILVERLIGHT符号时使用,即:

#if !SILVERLIGHT
[DataContract]
#endif
public class Class1 { /* ... */ }
如何将此#if/#endif块添加到Class1
CodeTypeDefinition
,或DataContract
CodeAttributeDeclaration

不确定如何获取发出的#if,但可以生成两个不同版本的类(一个带有DataContract属性,一个没有)并使用ConditionalAttribute(http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx)因此,每个环境都使用正确的

  CodeAttributeDeclaration declaration1 =
    new CodeAttributeDeclaration(
      "System.Diagnostics.ConditionalAttribute",
      new CodeAttributeArgument(
        new CodePrimitiveExpression("SILVERLIGHT")));

我不建议在生成的类中添加<代码> [DATACONTROUT] 属性,因为当类将被重写时,它将被重写。如果我是你,我会考虑将你的数据模型映射到DTOs(数据传输对象),使用解释的方法将具有<代码> [DATACONTROS] < /Cord>属性。


您可以使用来帮助您将模型映射到DTO。

我实际上决定做的是在生成代码文件后,通过Python脚本添加
\if/\endif
标记。Robert的回答在功能上是有效的,但我觉得使用两个单独的类并不合适,因为其中一个应该很好

虽然它在数据模型生成中引入了另一种语言,但这似乎是获得我想要的最干净的方法。我们正在使用的脚本如下所示。现在只需要检查不可序列化的属性(特别是在PropertyChanged事件上),因为我们采用了一种新的数据契约结构

#!/usr/bin/env python

import sys
from optparse import OptionParser
import shutil

# Use OptionParser to parse script arguments.
parser = OptionParser()

# Filename argument.
parser.add_option("-f", "--file", action="store", type="string", dest="filename", help="C# class file to parse", metavar="FILE.cs")

# Parse the arguments to the script.
(options, args) = parser.parse_args()

# The two files to be used: the original and a backup copy.
filename = options.filename

# Read the contents of the file.
f = open( filename, 'r' )
csFile = f.read()
f.close()

# Add #if tags to the NonSerialized attributes.
csFile = csFile.replace('        [field: NonSerialized()]',
                    '        #if !SILVERLIGHT\r\n        [field: NonSerialized()]\r\n        #endif')

# Rewrite the file contents.
f = open( filename, 'r' )
f.write(csFile)
f.close()

不是答案,但如果您刚刚开始,最好使用T4模板。不幸的是,我们并不是真正的“刚刚开始”--当我们准备将数据模型共享给Silverlight端时,出现了这个问题。代码是从我们不拥有的XSD文件生成的。我以前没有听说过T4模板,因此这可能是将来学习的内容。:)我对你的建议有点困惑,因为我试图在生成时添加DataContract属性。我以前没有听说过DTO,我也会尝试研究一下。