属性类,系统.属性,复杂类型

本文关键字:属性 类型 复杂 系统 | 更新日期: 2023-09-27 17:58:01

是否可以用复杂类型的字段和构造函数声明AttributeClass?

答案是:不!请参阅此帖子:https://stackoverflow.com/a/38509077/2935383

向下滚动查看其他解决方案。

我的尝试:

自有属性类

class Attr : System.Attribute {
    private string _author;
    private A[] _additionalParam;
    public string Author{ get { return _author; } }
    public A[] Add{ get { return _additionalParam; } }
    public Attr( string author, params A[] add ){
        _author = author;
        _additionalParam = add;
    }
}

复杂型

class A{
    public string abc;
    public string def;
    public A( string a, string b ){
        abc = a;
        def = b;
    }
}

使用属性类

//this dosn't work
[Attr("me ;)", new A("a","b"), new A("c", "d")] 
TestClass{
}

无法使用new A("a","b"),它不是常量。

编辑:构造函数也采用复杂类型;)


我的解决方案:

我已经定义了第二个属性类,并将其设置为多个。

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
class AdditionlAttr : System.Attribute
    public string abc;
    public string def;
    public AdditionlAttr( string a, string b ){
        abc = a;
        def = b;
    }
}

并更改Attr-类

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
class Attr : System.Attribute {
    private string _author;
    public string Author{ get { return _author; } }
    public Attr( string author ){
        _author = author;
    }
}

用法:

[Attr("me ;)"]
[AdditionlAttr("a","b")]
[AdditionlAttr("c","d")]
TestClass{
}

属性类,系统.属性,复杂类型

不,你不能这样做。来自C#语言规范5.0第17.1.3节:

属性类的位置参数和命名参数的类型仅限于属性参数类型,它们是:

  • 以下类型之一:boolbytechardoublefloatintlongsbyteshortstringuintulongushort
  • 类型object
  • 类型System.Type
  • 枚举类型[…]
  • 上述一维阵列

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