2011-08-31 67 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