【发布时间】:2014-08-07 19:53:59
【问题描述】:
我正在尝试使用 CodeDom 生成一些方法,在为这些方法生成自定义属性时遇到问题。
我可以管理简单的空属性,比如
[DataMember()]
或带有字符串值参数的属性,
[DataContract(Namespace = "http://somenamespace")]
但是我需要生成更复杂的属性,比如
[WebInvoke(Method = "POST", UriTemplate = "SomeTemplate", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
和
[FaultContract(typeof(Collection<MyFault>))]
对于枚举值ResponseFormat = WebMessageFormat.Json 的参数,我尝试了与字符串类似的方法,创建了一个 CodePrimitiveExpression 实例:
CodeAttributeDeclaration webInvoke = new CodeAttributeDeclaration()
{
Name = "WebInvoke",
Arguments =
{
new CodeAttributeArgument
{
Name = "Method",
Value = new CodePrimitiveExpression("POST")
},
new CodeAttributeArgument
{
Name = "UriTemplate",
Value = new CodePrimitiveExpression(method.Name)
},
new CodeAttributeArgument
{
Name = "RequestFormat",
Value = new CodePrimitiveExpression(WebMessageFormat.Json)
},
new CodeAttributeArgument
{
Name = "ResponseFormat",
Value = new CodePrimitiveExpression(WebMessageFormat.Json)
}
}
};
但是,这不起作用,我得到一个异常说
无效的原始类型:System.ServiceModel.Web.WebMessageFormat。考虑使用 CodeObjectCreateExpression。
我确实考虑过使用 CodeObjectCreateExpression,但我不知道如何使用。它需要一个字符串或一个 CodeTypeReference,并且需要一个 CodeExpression 参数数组作为第二个参数。我不知道该放什么参数。
至于另一个属性,typeof(Colleciton<MyFault>),我什至不知道从哪里开始。任何帮助将不胜感激。
编辑:有人建议我在尝试模仿的方法上调用 CustomAttributeData.GetCustomAttributes,所以我这样做了。为了效率和清晰起见,我将在屏幕截图中提供数据。这让我对我正在处理的内容有了一个更好的了解,但我仍然不确定如何实现它。
【问题讨论】:
标签: c# custom-attributes codedom