我有个问题:[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34230")]
对于windows 8和windows 7,在生成文件时,我们有不同版本的这个数字(4.0.30319.34230)。所以即使我生成新的东西,我在文件中也有变化,唯一改变的就是这个数字。
是否有一种方法不将此属性添加到生成的代码中,或者解决方案在Windows 8和Windows 7中具有相同的编号?
发布于 2016-09-28 16:18:17
我用tt文件中的以下代码解决了这个问题:
...
<#@ assembly name="$(SolutionDir)../res/ICSharpCode.NRefactory.dll" #>
<#@ assembly name="$(SolutionDir)../res/ICSharpCode.NRefactory.CSharp.dll" #>
<#@ import namespace="ICSharpCode.NRefactory.CSharp" #>
<#@ import namespace="System.CodeDom.Compiler" #>
...
<#+
public class XsdSchemaTransformer : CSharpTemplate
{
public void TransformSchemas(TransformationContext transformationContext)
{
...
foreach (string file in files)
{
...
string transformText = typesTemplate.Transform();
transformText = ModifyGeneratedCodeAttributeXmlVersionNumber(transformText);
typesTemplate.Context.Write(typesTemplate.Output, transformText);
}
}
private string ModifyGeneratedCodeAttributeXmlVersionNumber(string source)
{
CSharpParser parser = new CSharpParser();
SyntaxTree syntaxTree = parser.Parse(source);
IEnumerable<TypeDeclaration> typeDeclarations = syntaxTree.Descendants.OfType<TypeDeclaration>();
foreach (TypeDeclaration typeDeclaration in typeDeclarations)
{
AttributeSection generatedCodeAttributeSection = typeDeclaration.Attributes.FirstOrDefault(x => x.Attributes.FirstOrDefault(y => IsTypeOfGeneratedCodeAttribute(y.Type)) != null);
if (generatedCodeAttributeSection != null)
{
ICSharpCode.NRefactory.CSharp.Attribute generatedCodeAttribute = generatedCodeAttributeSection.Attributes.FirstOrDefault(x => IsTypeOfGeneratedCodeAttribute(x.Type));
PrimitiveExpression primitiveExpression = (PrimitiveExpression)generatedCodeAttribute.Arguments.ElementAt(1);
string xmlVersionNumber = Convert.ToString(primitiveExpression.Value);
string[] splittedVersionNumber = xmlVersionNumber.Split('.');
string formatedXmlVersionNumber = string.Format("{0}.{1}", splittedVersionNumber[0], splittedVersionNumber[1]);
generatedCodeAttribute.Arguments.Remove(primitiveExpression);
generatedCodeAttribute.Arguments.Add(new PrimitiveExpression(formatedXmlVersionNumber));
}
}
return syntaxTree.GetText();
}
private bool IsTypeOfGeneratedCodeAttribute(AstType type)
{
return type.ToString().Equals(typeof(GeneratedCodeAttribute).FullName);
}
}
#>结果是:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0")]https://stackoverflow.com/questions/28539310
复制相似问题