2011-08-31 68 views
0

我正在使用XSD - > C#类解析器,它为我们的数据模型生成类,它将在WPF客户端和Silverlight之间共享基于网络的部分。添加#if /#endif指令到DataContract属性生成类的CodeTypeDefinition

我们正试图与没有被定义Silverlight的符号时,才应使用[DataContract]属性,即以增强生成的类:

#if !SILVERLIGHT 
[DataContract] 
#endif 
public class Class1 { /* ... */ } 

我怎么能这样的#if/#ENDIF块添加到CodeTypeDefinition第1类,或CodeAttributeDeclarationDataContract

+0

不是一个答案,但如果你刚刚开始这个,你最好使用T4模板。 – Jeff

+0

不幸的是,我们并不是真的“刚刚开始” - 当我们准备将数据模型分享给Silverlight方面时,这个问题就突然出现了。该代码是由我们不拥有的XSD文件生成的。我之前没有听说过T4模板,所以这可能是未来学习的东西。 :) – dythim

回答

0

我实际上决定做的是在代码文件生成后,通过Python脚本添加#if/#endif标签。罗伯特的答复在功能上是有效的,但我只是觉得不对,只有一个应该就好了。

虽然它在数据模型生成中引入了另一种语言,但这看起来像是获得我想要的最干净的方法。我们正在使用的脚本如下。现在只需要检查NonSerializable属性(特别是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() 
1

不知道如何获得#if的发射,但是您可以生成两个不同版本的类(一个带有DataContract属性,一个没有)并使用ConditionalAttribute(http://msdn.microsoft.com/zh-cn/对他们我们/库/ system.diagnostics.conditionalattribute.aspx),所以正确的使用为每个环境

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

我不会建议增加对生成的类的属性[DataContract],因为它会被覆盖时该课程将重新生成。如果我是你,我会考虑使用方法Robert Levy解释你的数据模型映射到DTO(数据传输对象),该数据将具有[DataContract]属性。

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

+0

我有点困惑你的建议,因为我想添加DataContract属性__at__生成时间。我以前没有听说过DTO的,我也会试着去看看那些。 – dythim