You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CodeDom生成附带自定义特性的自动属性

方案1:直接把特性写入代码片段

CodeSnippetTypeMember属于纯文本插入节点,它的特性集合不会被CodeDom引擎解析渲染,直接把特性内容拼到片段文本中即可解决问题:

CodeTypeDeclaration newType = new CodeTypeDeclaration("TestType");
CodeSnippetTypeMember snippet = new CodeSnippetTypeMember();

snippet.Comments.Add(new CodeCommentStatement("这是带特性的自动属性", true));
// 直接把特性和属性定义都写入片段文本
snippet.Text = @"[FindsBy(How = How.Id, Using = ""AllTabs"")]
public IWebElement SaveButton { get; set; }";

newType.Members.Add(snippet);

方案2:使用标准CodeMemberProperty实现(更灵活,支持动态配置)

不需要硬编码文本,使用CodeDom原生的属性声明结构,只要不给get/set访问器添加任何实现语句,生成时就会自动输出自动属性语法,同时可以正常附加自定义特性:

// 声明属性基础信息
CodeMemberProperty saveBtnProp = new CodeMemberProperty();
saveBtnProp.Name = "SaveButton";
saveBtnProp.Type = new CodeTypeReference(typeof(IWebElement));
saveBtnProp.Attributes = MemberAttributes.Public | MemberAttributes.Final;

// 添加FindsBy特性
CodeAttributeDeclaration findsByAttr = new CodeAttributeDeclaration("FindsBy");
findsByAttr.Arguments.Add(new CodeAttributeArgument("How", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(How)), "Id")));
findsByAttr.Arguments.Add(new CodeAttributeArgument("Using", new CodePrimitiveExpression("AllTabs")));
saveBtnProp.CustomAttributes.Add(findsByAttr);

// 声明空的get/set访问器,生成后自动转为自动属性语法
saveBtnProp.HasGet = true;
saveBtnProp.HasSet = true;

// 加入类型成员集合
newType.Members.Add(saveBtnProp);

两种方案都可以正常生成符合要求的代码,第二种更适合需要动态拼接属性名、特性参数的场景。


内容的提问来源于stack exchange,提问作者Saddam Hussain I H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:15:01