C#属性参数类型:是否允许其他属性? [英] C# attribute parameter type: does it allow another Attribute?

查看:55
本文介绍了C#属性参数类型:是否允许其他属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是对使用C#感兴趣的开发人员.我感兴趣的功能是Attribute(在Java中称为注释).

I am a developer interested in working with C#. The feature I'm interested in is Attribute (called annotation in Java).

我的问题是:属性参数类型是否支持使用其他属性?

My question is: Does attribute parameter type support the use of another Attribute?

在C#语言规范的第17.1.3节中,其规定如下:

In Section 17.1.3 of the C# language specification, it states the followings:

" ...

"...

属性类的位置和命名参数的类型限于以下属性参数类型:

The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

  • 以下类型之一:bool,byte,char,double,float,int,long,sbyte,short,string,uint,ulong,ushort.
  • 类型对象.
  • 类型System.Type.
  • 枚举类型,只要它具有公共可访问性,并且嵌套的类型(如果有)也具有公共可访问性(第17.2节).
  • 上述类型的一维数组.

没有这些类型之一的构造函数参数或公共字段不能用作属性规范中的位置参数或命名参数.

A constructor argument or public field which does not have one of these types, cannot be used as a positional or named parameter in an attribute specification.

..."

..."

我很好奇第二种类型(类型对象)是否还意味着可以使用Attribute.因为据我所知,Object是所有引用类型(?)的超类型.

I am curious whether the second type (type object) also means that Attribute can be used. Because, as far as I know Object is the supertype of all referenced types (?).

为了说明,我想实现以下目标:

To illustrate, I want to achieve something like the following:

[MyAttribute("abc",p1 ="...", p2 = [AnotherAttribute("123")] )]

[ MyAttribute( "abc", p1="...", p2=[ AnotherAttribute("123") ] ) ]

class MyClass { ...}

class MyClass {  ... }

其中:MyAttribute和AnotherAttribute是属性,参数MyAttribute.p2声明为AnotherAttribute类型.

where: MyAttribute and AnotherAttribute are attributes, and parameter MyAttribute.p2 is declared with the type AnotherAttribute.

非常感谢您的回复.

推荐答案

还有另一份文档实际上更详细地说明了这一点(

  • 简单类型(bool,byte,char,short,int,long,float和double)
  • 字符串
  • System.Type
  • 枚举
  • 对象(类型为object的属性参数的参数必须为上述类型之一的常量值.)
  • 任意一维数组以上类型
  • 因此,我要说的是,您的问题的答案是否定的,您不能那样做.即使可以将属性参数声明为类型对象,您传递的实际参数也必须是常量字符串,布尔值等(将其声明为对象) 只是意味着您可以在每次声明属性时使用这些类型中的任何一种.

    So going by this, I would say the answer to your question is no, you cannot do that. Even though you can declare an attribute parameter as type object, the actual argument you pass in must still be a constant string, bool, etc (declaring it as an object just means you can use any of these types each time you declare the attribute).

    如果您要说明要实现的目标,则可能会有所帮助,因为典型的情况是您只需将两个属性都放在类上.例如:

    It may help if you stated what you are trying to achieve, because the typical situation is you would just place both attributes on the class. E.g.:

    [MyAttribute("abc")]
    [AnotherAttribute("123")]
    class MyClass {...}


    这篇关于C#属性参数类型:是否允许其他属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆