我有生成此构造函数的代码:
public C001(string p8179_010, string p1131_020, string p3055_030, string p8178_040)
{
this.@__E8179_010 = p8179_010;
this.@__E1131_020 = p1131_020;
this.@__E3055_030 = p3055_030;
this.@__E8178_040 = p8178_040;
}
这是创建上述代码的代码的子集:
CodeTypeDeclaration classDecl = new CodeTypeDeclaration()
{
Name = string.Format( "{0}", node.XPathSelectElement( "Code" ).Value ),
IsClass = true
};
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public | MemberAttributes.Final;
classDecl.Members.Add( constructor );
foreach ( var component in node.XPathSelectElements( "Components/Component" ) )
{
string componentBackingField = string.Format( "__{0}_{1}", componentRef, component.XPathSelectElement( "Position" ).Value );
string constructorParameterRef = string.Format( "p{0}_{1}", component.XPathSelectElement( "Element" ).Value, component.XPathSelectElement( "Position" ).Value );
constructor.Parameters.Add( new CodeParameterDeclarationExpression( typeof( System.String ), constructorParameterRef ) );
CodeFieldReferenceExpression paramRef = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), componentBackingField );
constructor.Statements.Add( new CodeAssignStatement( paramRef, new CodeArgumentReferenceExpression( constructorParameterRef ) ) );
}
由于我对CodeDOM的经验有限,我该如何修改它以便它执行此操作:
public C001(string p8179_010, string p1131_020, string p3055_030, string p8178_040)
{
this.@__E8179_010.Value = p8179_010;
this.@__E1131_020.Value = p1131_020;
this.@__E3055_030.Value = p3055_030;
this.@__E8178_040.Value = p8178_040;
}
不同之处在于我想将参数分配给它的后备字段的Value
属性。
答案 0 :(得分:1)
我已经设法弄清楚了,但我不确定这是最干净的方法。
我改变了这个:
CodeFieldReferenceExpression paramRef =
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), componentBackingField );
到此:
CodeFieldReferenceExpression paramRef =
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(), string.format("{0}.Value", componentBackingField ));
它有效!
答案 1 :(得分:0)
你必须像编译器一样思考:使用树(特别是语法树)。当您编写this.@__E8179_010.Value
时,编译器会看到如下内容:
现在,当您使用.
访问字段时,它表示为CodeFieldReferenceExpression
,树中的两个子项是其构造函数中的两个参数。
这意味着上面的树可以写成:
new CodeFieldReferenceExpression( // second (upper) .
new CodeFieldReferenceExpression( // first (lower) .
new CodeThisReferenceExpression(), componentBackingField),
"Value")
或者,如果您不想打扰所有这些并且喜欢字符串,只需使用CodeSnippetExpression
(或可能使用其他CodeSnippet*
类型):
new CodeSnippetExpression(string.Format("this.{0}.Value", componentBackingField))