【问题标题】:Complex attribute declaration for methods in CodeDomCodeDom 中方法的复杂属性声明
【发布时间】: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


    【解决方案1】:

    WebMessageFormat.Json 这样的表达式看起来像访问一个静态字段,所以你必须这样写:

    new CodeAttributeArgument
    {
        Name = "RequestFormat",
        Value = new CodeFieldReferenceExpression(
            new CodeTypeReferenceExpression("WebMessageFormat"), "Json")
    }
    

    typeof 表达式是一种特殊类型的表达式,所以它有自己的 CodeDOM 类型:

    new CodeAttributeDeclaration(
        "FaultContract",
        new CodeAttributeArgument(new CodeTypeOfExpression("Collection<MyFault>")))
    

    要查看 CodeDOM 中所有可用表达式类型的列表,请查看 the inheritance hierarchy in the docs of CodeExpression

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-15
      • 2011-10-24
      • 1970-01-01
      • 2014-02-06
      • 1970-01-01
      相关资源
      最近更新 更多